Frontend Patterns

Pattern

State Colocation

Keep state as close as possible to where it's used to reduce complexity. (See also: Colocation Pattern)

State Management Intermediate

State Colocation

Problem

State stored far from where it’s actually used creates unnecessary coupling and complexity. Global stores fill up with UI-specific state like modal visibility or form input values. Components re-render unnecessarily when unrelated state changes, and debugging becomes difficult because state mutations can come from anywhere in the application.

Solution

Keep state as close as possible to where it’s used rather than lifting it higher than necessary. This simplifies components and reduces coupling between distant parts of the tree.

Example

This demonstrates keeping state close to where it’s actually used rather than lifting it unnecessarily high, simplifying components and reducing coupling across the application.

// Colocate state with component that uses it
class SearchBar extends HTMLElement {
  constructor() {
    super();
    this.query = ''; // State only used within this component - kept local
  }

  connectedCallback() {
    this.render();
    this.querySelector('input').addEventListener('input', (e) => {
      this.query = e.target.value;  // Update local state
      this.render();                // Re-render only this component
    });
  }

  render() {
    // State is used right here, no need to pass through multiple layers
    this.innerHTML = `<input type="text" value="${this.query}">`;
  }
}

Benefits

  • Simplifies components by keeping state local and focused.
  • Reduces unnecessary re-renders in components that don’t need the state.
  • Makes code easier to understand and maintain.
  • Enables better code splitting since state isn’t globally shared.

Tradeoffs

  • May need to lift state later if requirements change and state needs sharing.
  • Can lead to state duplication if components accidentally maintain separate copies.
  • Requires judgment about what constitutes “close enough” to the usage.
  • May conflict with global state management patterns.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.