Consider this React component that updates a counter on button clicks. What will be the displayed count after clicking the button once?
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 1); } return ( <div> <p>Count: {count}</p> <button onClick={handleClick}>Increment Twice</button> </div> ); } export default Counter;
Remember that state updates in React are asynchronous and may be batched.
Both setCount calls use the same stale value of count (which is 0). So the state is set to 1 twice, resulting in a final count of 1, not 2.
In React functional components, which hook runs after every render including the first render and all updates?
Think about which hook runs after every render regardless of dependencies.
useEffect without a dependency array runs after every render, including the first and all updates.
What error will this React component produce when the button is clicked?
import React, { useState } from 'react'; function Example() { const [value, setValue] = useState(0); function handleClick() { setValue(value + 1); setValue(value + 1); } return ( <div> <p>{value}</p> <button onClick={handleClick}>Update</button> </div> ); } export default Example;
Consider how React batches state updates with the same value source.
Both setValue calls use the same stale value (0), so the final state is 1, not 3 or 2.
This React component updates state but does not re-render. Why?
import React, { useState } from 'react'; function NoRender() { const [obj, setObj] = useState({ count: 0 }); function increment() { obj.count += 1; setObj(obj); } return ( <div> <p>{obj.count}</p> <button onClick={increment}>Increment</button> </div> ); } export default NoRender;
Think about how React compares previous and new state values.
React uses shallow comparison for state. Since the object reference does not change, React skips re-render.
Arrange the steps React follows during the updating phase after a state change.
Think about React's render and commit phases and when effects run.
React first renders the component (1), then compares the new JSX with the old (3), then commits changes to the DOM (2), and finally runs effects (4).