0

Why does setState accept a callback function, and when should this pattern be used in React?

author
subina kallyani
easy
0
0

Answer

The callback function form of setState is used when the new state depends on the previous state.

React state updates can be asynchronous and batched, so relying directly on the current state value may lead to incorrect results.

Normal setState (Problem Case)

setCount(count + 1);

If multiple updates happen together, count may be stale, causing wrong values.


Callback Function Form (Correct Way)

setCount((prevCount) => prevCount + 1);

Here, React provides the latest state value, ensuring the update is accurate.


Why this matters

  • State updates may not happen immediately
  • Multiple state updates can be grouped together
  • The callback form avoids race conditions

When should you use it?

Use the callback function form when:

  • The new state depends on the previous state
  • Updating counters, toggles, or accumulative values
  • Multiple state updates happen in the same render cycle

Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0