Course contentsShow
← React
Lesson 418 of 2,39612. Rendering and BatchingFree lesson

Automatic Batching in Event Handlers

Learn how React automatically batches all state updates within event handlers like onClick.

Automatic Batching in Event Handlers

What you'll learn: How React automatically combines multiple state updates inside event handlers into a single re-render for better performance.

The Core Idea

When you call multiple setState functions inside an event handler (like onClick, onChange, etc.), React doesn't immediately re-render after each one. Instead, it intelligently batches all those updates together and performs just one re-render at the end.

This is automatic batching in action—and it happens by default in all React event handlers.

Why This Matters

Imagine clicking a button that updates three different pieces of state:

function handleClick() {
  setCount(count + 1);
  setFlag(true);
  setName('Alex');
}

Without batching, React would re-render three times—once after each setState. That's wasteful! With automatic batching, React collects all three updates, processes them together, and renders just once with all the new values.

The Analogy

Think of batching like grocery shopping. You don't drive to the store separately for milk, then bread, then eggs. You make one trip and buy everything together. React does the same with state updates inside event handlers—one "trip" (re-render) handles all the updates.

What You'll Notice

Inside an event handler, even if you call setState multiple times, you won't see intermediate renders. React waits until your event handler finishes running, then batches everything and commits once.

This is why event handlers are the perfect place to update multiple related pieces of state—React handles the optimization automatically.

Key Takeaway: React automatically batches all state updates within event handlers into a single re-render, making your app faster without any extra effort from you.