Intermediate React Interview QuestionsIntermediatePractical
React · Question 34
When should you use the functional form of a React state setter?
Direct answer
Use a functional updater when the next state depends on the previous state, especially when multiple updates may be queued before React renders again.
Counter.jsx
function Counter() {
const [count, setCount] = useState(0);
function addThree() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return <button onClick={addThree}>{count}</button>;
}Each updater receives the result of the previous queued update. This makes setCount(c => c + 1) reliable even when several increments are queued from the same event.