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 MachinesWhen 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 → View3. 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:
- Flux Architecture - Redux patterns and best practices
- Atom-Based State - Recoil and Jotai patterns
- Signals - Solid.js-inspired reactivity
- State Machines - XState patterns
- Undo/Redo - History management
- Optimistic UI - Advanced patterns
- Persistence - State persistence strategies
- 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, verboseWhen 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
- Choose the right tool for the problem size
- Co-locate state when possible
- Derive don't duplicate state
- Normalize data (flat structures)
- Memoize selectors to prevent re-renders
- Type your state with TypeScript
- Test state logic independently
- Document state structure
- Monitor performance (re-renders)
- Version state for migrations
Next Steps
Explore each pattern in this section to find the right state management solution for your application's needs.