React Developers: Why do three setState calls result in count being 0?

🚀 React Developers — Can you answer this tricky questions? This look simple, but this question test deep understanding of React’s rendering cycle, batching, and hooks. ✅ Most guess the value is 3 — but it’s actually 0. ✅ Why? React batches multiple state updates in the same event loop. All three setCount(count + 1) calls use the same stale value (0). So the state updates only once → new count becomes 1. And console.log(count) prints the old render value (0) because state updates apply after re-render. #reactjs #frontenddevelopment #javascript #reacthooks #reactinterview #webdevelopment #nextjs #reacttips #frontendengineer #seniorfrontend #programming #womenintech #softwaredevelopment #developers #codingtips #learnreact

  • text

Because useState updates are asynchronous so, when you call setCount(count+1) synchronously in the same function, all of them uses the same previous value of count-- because count is not immediately updated after each setCount. (UI-1) And console.log() will give 0 as output because it will run before React re-renders.

Like
Reply

In your JSX function, when you click the button, the output of console.log(count) will be the current value of count before any updates—so it will log 0 on the first click. Why? • useState updates are asynchronous and batched. • All three setCount(count + 1) calls use the same stale value (count), so they don’t increment as you might expect. • The console.log(count) runs before React processes the updates. If you want to increment by 3 reliably, use the updater function: setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); Or even better: setCount(c => c + 3); Summary: • Output will be 0 (the value before updates) on the first click. • The displayed count will increase by 1, not 3.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories