0 day streak
javascript / intermediate
Snippet

Functional Updates for Stale State

Passing a function to the state setter ensures you are working with the most up-to-date state value, avoiding bugs in asynchronous updates.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const [count, setCount] = useState(0);
const incrementTwice = () => {
// Bad: Uses stale 'count' value twice
// setCount(count + 1); setCount(count + 1);
// Good: Uses function to access most recent state
setCount(prev => prev + 1);
setCount(prev => prev + 1);
};
nextjs
Breakdown
1
setCount(prev => prev + 1);
The 'prev' argument represents the latest state, even if multiple updates are queued.