Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
State might seem like a regular variable that you can read and write. However, state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render with a new snapshot.
React batches multiple state updates together. This means that if you call setState multiple times in the same event, React will wait until the end to apply all updates at once.
Don't expect to read the updated state immediately after calling setState:
setCount(count + 1);
console.log(count); // โ Still the old value!Don't use current state to calculate the next state in a loop:
// โ This won't work as expected
for (let i = 0; i < 5; i++) {
setCount(count + 1); // Always uses the same count!
}Use the functional form when you need the previous state:
// โ
This works correctly
for (let i = 0; i < 5; i++) {
setCount(prevCount => prevCount + 1);
}State variables don't change during a render. Each render sees its own "snapshot" of state.
Multiple state updates in the same event are batched together for better performance.
Setting state doesn't change the current variable, but schedules a new render with the updated value.
When you need the previous state, use the functional form: setState(prev => prev + 1).