Frontend Patterns

Pattern

State Batching

Group multiple state updates together to minimize re-renders and improve performance.

State Management Intermediate

State Batching

Problem

Multiple state updates in rapid succession trigger separate re-renders for each change, causing performance bottlenecks and visual flashing. Users see components flash through intermediate states. Event handlers that update several related state values cause the component tree to render multiple times, wasting CPU cycles and degrading user experience.

Solution

Group multiple state updates into a single re-render to improve performance. This reduces unnecessary work when updates would result in the same final state.

Example

This demonstrates grouping multiple state updates into a single render cycle to minimize re-renders, improve performance, and prevent visual flashing through intermediate states.

// Framework-agnostic state batching
class Component extends HTMLElement {
  constructor() {
    super();
    this.count = 0;
    this.flag = false;
    this.pendingUpdate = false;
  }

  scheduleUpdate() {
    if (!this.pendingUpdate) {
      this.pendingUpdate = true;
      // Batch updates using microtask queue - defers render until after all synchronous code
      queueMicrotask(() => {
        this.render();  // Single render for all state changes
        this.pendingUpdate = false;
      });
    }
  }

  handleClick() {
    // Multiple state updates happen synchronously
    this.count++;
    this.flag = !this.flag;
    // But only one render is scheduled
    this.scheduleUpdate();
  }

  render() {
    this.innerHTML = `<button>Count: ${this.count}</button>`;
  }
}

Benefits

  • Dramatically improves performance by reducing re-render count.
  • Eliminates visual flashing through intermediate states.
  • Makes updates feel atomic and instantaneous.
  • Reduces CPU cycles wasted on redundant rendering work.

Tradeoffs

  • Automatic batching may delay state updates until after event handlers complete.
  • Can make debugging harder when trying to understand update timing.
  • May hide race conditions or timing issues during development.
  • Requires understanding when updates are batched versus when they aren’t.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.