Front-end Engineering Lab
Patterns

State and Logic Patterns

Advanced state management patterns for complex applications

State management is one of the most critical aspects of frontend development. This section covers advanced patterns beyond basic React state.

Why Advanced State Management?

Basic: useState, useContext
Advanced: Flux, Atoms, Signals, State Machines

When you need it:

  • Global state across many components
  • Complex state logic
  • Time travel / undo-redo
  • Optimistic updates
  • State persistence
  • Cross-tab synchronization

State Management Evolution

1. Component State (2013)

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

2. Flux Pattern (2014)

Action → Dispatcher → Store → View

3. Atom-Based (2020)

const countAtom = atom(0);

4. Signals (2022)

const count = signal(0);

5. State Machines (XState)

const machine = createMachine({...});

Coverage

This section includes:

  1. Flux Architecture - Redux patterns and best practices
  2. Atom-Based State - Recoil and Jotai patterns
  3. Signals - Solid.js-inspired reactivity
  4. State Machines - XState patterns
  5. Undo/Redo - History management
  6. Optimistic UI - Advanced patterns
  7. Persistence - State persistence strategies
  8. Cross-Tab Sync - BroadcastChannel patterns

Quick Comparison

// React Context (Built-in)
const ThemeContext = createContext();
// Pros: Built-in, simple
// Cons: Re-renders, no selectors

// Redux (Flux)
const store = configureStore({ reducer });
// Pros: Predictable, DevTools, middleware
// Cons: Boilerplate, learning curve

// Recoil/Jotai (Atoms)
const countAtom = atom(0);
// Pros: Fine-grained, minimal boilerplate
// Cons: Less mature ecosystem

// Signals
const count = signal(0);
// Pros: Extremely fast, automatic tracking
// Cons: Different mental model

// XState (State Machines)
const machine = createMachine({...});
// Pros: Impossible states impossible, visualizable
// Cons: Learning curve, verbose

When to Use What

Component State

  • Local UI state
  • Forms (simple)
  • Toggles, counters

Context

  • Theme
  • Auth
  • 2-3 levels deep

Redux/Flux

  • Large apps
  • Time travel needed
  • Team familiarity

Atoms (Recoil/Jotai)

  • Fine-grained subscriptions
  • Derived state
  • Async selectors

Signals

  • Maximum performance
  • Real-time updates
  • Gaming, animations

State Machines

  • Complex workflows
  • Multi-step forms
  • Impossible states must be prevented

Best Practices

  1. Choose the right tool for the problem size
  2. Co-locate state when possible
  3. Derive don't duplicate state
  4. Normalize data (flat structures)
  5. Memoize selectors to prevent re-renders
  6. Type your state with TypeScript
  7. Test state logic independently
  8. Document state structure
  9. Monitor performance (re-renders)
  10. Version state for migrations

Next Steps

Explore each pattern in this section to find the right state management solution for your application's needs.

On this page