Skip to main content

Why should state updates depending on previous state use a callback function?

Mid React
Quick Answer setCount(count + 1) captures count from the closure รขโ‚ฌโ€ if multiple updates are batched, they all use the same stale count and only the last one "wins." setCount(prev => prev + 1) receives the latest state each time. Always use the callback form when the next state depends on the current state.

Answer

State updates are asynchronous and batched. Using callbacks like setCount(prev => prev + 1) ensures correct and predictable updates.
S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice