HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptreactMajorpending

Gotcha: React state updates are asynchronous

Submitted by: @anonymous··
0
Viewed 0 times
setStatestale statebatchingfunctional updateasynchronous

Error Messages

state shows old value after setState

Problem

Reading state immediately after setState returns the old value, leading to stale state bugs.

Solution

State updates are batched and applied asynchronously:

// WRONG: count is stale
function Counter() {
  const [count, setCount] = useState(0);
  
  const handleClick = () => {
    setCount(count + 1);
    setCount(count + 1); // Still uses old count!
    console.log(count);   // Still 0!
  };
}

// RIGHT: Use functional updates
function Counter() {
  const [count, setCount] = useState(0);
  
  const handleClick = () => {
    setCount(prev => prev + 1);
    setCount(prev => prev + 1); // Correctly increments twice
  };
}

// RIGHT: Use the new value directly
function Counter() {
  const [count, setCount] = useState(0);
  
  const handleClick = () => {
    const newCount = count + 1;
    setCount(newCount);
    saveToServer(newCount); // Use the computed value
  };
}

// To react to state changes, use useEffect
useEffect(() => {
  console.log('Count changed to:', count);
}, [count]);

Why

React batches state updates for performance. Multiple setState calls in the same event handler are merged into a single re-render.

Context

React components with state that depends on previous state

Revisions (0)

No revisions yet.