Course contentsShow
← React
Lesson 678 of 2,39618. When NOT to Use useEffectFree lesson

When Events Need State: Reading Current State

Using functional state updates and current state values directly in event handlers without effects.

When Events Need State: Reading Current State

What you'll learn: How event handlers naturally access the latest state without needing useEffect.

The Core Idea

When a user clicks a button or submits a form, your event handler automatically has access to the current state at the moment it runs. You don't need an effect to "watch" state and react to it—the event handler reads state directly when the event happens.

This is React's built-in design: event handlers capture the most recent state values from the render they were created in. When state changes and React re-renders, new event handlers are created with fresh state values baked in.

Why This Works

Think of it like a vending machine: when you press button B3, the machine checks its current inventory at that moment. It doesn't need a separate monitoring system running constantly—the button press itself triggers the inventory check.

Similarly, when onClick fires, your handler function reads count or userName or whatever state you reference. That value is current because React just re-rendered with the latest state.

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    // ✅ count is CURRENT when this runs
    console.log('Current count:', count);
    setCount(count + 1);
  }

  return <button onClick={handleClick}>Clicked {count} times</button>;
}

No useEffect needed. The handler reads state naturally.

The Functional Update Alternative

If you need to update state based on state, use the functional form:

setCount(prevCount => prevCount + 1); // Always safe

This works even if count hasn't been re-rendered yet.

Key Takeaway: Event handlers already read current state when they run—effects are unnecessary for event-driven logic that needs state values.