ReactInterview preparation
Foundation·Concept·2 min read

Why should I use a functional state update?

Practice this question

Definition:

A functional state update supplies a function that receives the pending previous state and returns the next state. It is useful when several updates may be queued or a callback holds an older render's value. React can apply these updater functions in order without each relying on the same captured value.

Key points:

  • Use setCount(c => c + 1) when the next value depends on the previous value.

  • It avoids reading an old value from a closure during queued updates.

  • setCount(count + 1) twice in one handler usually adds only one.

  • Updater functions should be pure; do not send requests or mutate external data inside them.

Example — inside an event handler:

jsx
setCount(count + 1);
setCount(count + 1); // Both use the same render's count: usually +1 total.

// Alternative:
setCount(c => c + 1);
setCount(c => c + 1); // Each uses the pending previous value: +2 total.
  • These are two alternative approaches, not four calls intended to be used together.

Interview point:

  • State is a snapshot for a render, so reading it immediately after calling a setter does not give the next render's value.
Adapted from 06_REACT_NEXTJS.md · “Why should I use a functional state update?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.