React State Update Gotcha: Using Functional Updates

I used to think I understood React state… until this small thing proved me wrong. I wrote this: setCount(count + 1) setCount(count + 1) setCount(count + 1) And I was expecting the count to go up by 3. But it only increased by 1. At first, it made no sense. Then I realized what was actually happening… React doesn’t update state immediately. It batches those updates and runs them later. So all three lines were using the same old value of `count`. Basically, I was doing: 0 → 1, 0 → 1, 0 → 1 Final result: 1 That’s when I learned to use functional updates: setCount(prev => prev + 1) Now each update gets the latest value: 0 → 1 → 2 → 3 Such a small change, but it completely fixed the logic. Since then, I follow one simple rule: 👉 If the new state depends on the previous one, always use a function. It’s one of those things that seems obvious later… but only after it breaks your code once 😅 Curious — has something like this ever confused you in React? #react #javascript

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories