0
0
Reactframework~3 mins

Why Callback functions for state updates in React? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny change in updating state can save you from confusing bugs!

The Scenario

Imagine you have a counter that updates its value based on the previous count. You try to update the count multiple times quickly, but the displayed number doesn't match what you expect.

The Problem

Updating state directly without considering the previous value can cause bugs because React batches updates. This means your new state might overwrite the old one unexpectedly, leading to wrong or stale values.

The Solution

Using callback functions for state updates lets React safely use the latest state value. Instead of guessing the current state, you provide a function that receives it, ensuring your update is always correct.

Before vs After
Before
setCount(count + 1);
setCount(count + 1);
After
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 1);
What It Enables

This approach enables reliable and predictable state changes even when updates happen quickly or depend on previous values.

Real Life Example

Think of a like button that increments a count each time you click fast. Using callback functions ensures the count increases correctly every time without missing clicks.

Key Takeaways

Direct state updates can cause bugs when relying on old values.

Callback functions receive the latest state to update safely.

This makes your app's behavior consistent and bug-free.