Q6: How does useState work internally and why is state batching used?

useState stores state variables inside the component Fiber node's linked list of hooks. Calling a state setter function enqueues a update action on the Fiber queue. React batches multiple state updates within event handlers into a single re-render cycle to optimize performance.

Functional State Updates & Automatic Batching
function Counter() {
  const [count, setCount] = useState(0);

  const handleMultipleIncrements = () => {
    // Functional updates queue operations on Fiber state queue
    setCount(prev => prev + 1);
    setCount(prev => prev + 1);
    // React batches these calls into a single component re-render pass
  };
  return <button onClick={handleMultipleIncrements}>Count: {count}</button>;
}
💡 Functional state updates evaluate sequentially against the queued Fiber state, updating count safely to 2.
Key Takeaways
  • Hook states are preserved inside a linked list attached to the component Fiber instance.
  • Automatic batching (React 18) combines multiple state updates into single re-render updates.
Knowledge Check

Why should you pass a callback function to setState (setCount(prev => prev + 1)) when new state depends on previous state?