0 day streak
javascript / intermediate
Snippet

Safe State Updates with Functional Updates

When updating state based on its previous value, especially in async closures, use a functional update to ensure you are working with the most recent state version.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
function Counter() {
const [count, setCount] = useState(0);
const handleAsyncIncrement = () => {
setTimeout(() => {
setCount(prev => prev + 1);
}, 1000);
};
return <button onClick={handleAsyncIncrement}>Count: {count}</button>;
}
react
Breakdown
1
setCount(prev => prev + 1);
Passes a callback function that receives the latest pending state as an argument.