Course contentsShow
← React
Lesson 372 of 2,39611. useState Patterns and PitfallsFree lesson

Functional Updates in Event Handlers

Using setCount(c => c + 1) in onClick handlers to avoid stale closures when the same handler fires rapidly.

Functional Updates in Event Handlers

What you'll learn: How to use setCount(c => c + 1) inside onClick handlers to prevent stale state when events fire quickly.

The Problem: Rapid Clicks with Stale Closures

When you attach an event handler like onClick to a button, that function "closes over" the state value from the render when it was created. If the user clicks multiple times before React re-renders, each click may reference the same old state value, causing updates to be lost.

// ❌ Problematic with rapid clicks
<button onClick={() => setCount(count + 1)}>
  Click me fast!
</button>

If count is 0 and the user triple-clicks rapidly, all three handlers might read count as 0, resulting in setCount(1) three times—final count: 1 (not 3!).

The Solution: Functional Updates

Use the updater function form you learned earlier inside your event handlers:

// ✅ Safe for rapid clicks
<button onClick={() => setCount(c => c + 1)}>
  Click me fast!
</button>

Now each update reads the latest state React knows about, not the stale closure value. Triple-click? React guarantees: 0 → 1 → 2 → 3.

Why It Matters for Events

Event handlers are especially prone to this because:

  • Users can trigger them faster than re-renders happen
  • Multiple events can queue before React processes updates
  • Each handler is a separate closure capturing state at creation time

Using setCount(c => c + 1) ensures React chains updates sequentially, regardless of how fast the events fire.

Key Takeaway: Always use functional updates setState(prev => ...) in event handlers when the new state depends on the old state—it protects against stale closures from rapid user interactions.