Interview frequency: …
Short answer
A Functional Updater reads the latest state in the update queue and calculates the next value from it, even with multiple batched updates or stale closures (Stale Closures).
Explanation
React batches state updates. If you call setCount(count + 1) three times in a row in one event handler, each call reads the same initial count and increases it only once. setCount(c => c + 1) instead receives the previous queued value and increments three times.
Code example
// Correct cumulative increment example
function Counter() {
const [count, setCount] = useState(0);
const incrementThreeTimes = () => {
setCount(prev => prev + 1);
setCount(prev => prev + 1);
setCount(prev => prev + 1); // The final result will be 3
};
return <button onClick={incrementThreeTimes}>Value: {count}</button>;
}Common mistakes
- Using setCount(count + 1) in asynchronous functions such as setTimeout or chained operations, causing Stale State.