Skip to content

State update batching causes stale UI

Quick summary

You called setState multiple times in one handler and read state between calls — React batches updates so intermediate reads are stale.

Why this happens

  • You read state after a setState call in the same event handler, but React has not re-rendered yet

  • Multiple setState calls are batched into one render, so the state variable still holds the old value between calls

  • You expected each setState to immediately update the state variable, but updates are asynchronous and batched

Minimal example

✗ Broken code
function handleClick() {
  setCount(count + 1);
  console.log(count); // stale!
  setCount(count + 1); // adds 1 to old count, not new count
}
✓ Fixed code
function handleClick() {
  setCount(prev => prev + 1);
  setCount(prev => prev + 1); // correctly adds 2 total
}
// Or: setCount(count + 2);

Functional updates receive the latest state as an argument, so each update builds on the previous one even when batched.

How to diagnose

  • Log the state value right after setState to confirm it still shows the old value

  • Check if you are reading state in the same handler where you update it — the value will be stale until re-render

  • Use React DevTools to see the batched updates and the final state after the handler completes

How to fix

  • Use functional updates to chain state changes: setCount(prev => prev + 1) instead of setCount(count + 1)

  • Compute the new value locally before calling setState: const newCount = count + 1; setCount(newCount);

  • Use a single state object or useReducer to update multiple related values atomically

How to prevent

  • Never read state immediately after setState in the same handler — use functional updates or local variables

  • Use useReducer for complex state logic that involves multiple related updates

Related Resources

Related Glossary

Related Lessons

← Back to language