javascript / intermediate
Snippet
Safe State Logic with Functional Updates
When your state update depends on the previous state, you should pass a function to the setter. This ensures you are always working with the most recent state value, avoiding bugs caused by stale closures in asynchronous code or multiple rapid updates.
snippet.js
javascript
1
2
3
4
const increment = () => {setCount(prev => prev + 1);setCount(prev => prev + 1);};
react
Breakdown
1
setCount(prev => prev + 1);
Uses the previous state value 'prev' to calculate the new state safely.
2
setCount(prev => prev + 1);
Even if called twice in a row, each call receives the correctly updated value from the last step.