Single Store
Problem
State scattered across multiple locations makes it impossible to understand the full application state at any given time. Debugging requires checking countless component instances and context providers. Time-travel debugging and state persistence become impractical. Coordinating updates across different state containers leads to race conditions and inconsistent UI.
Solution
Centralize all application state in one store with a single update mechanism. This simplifies state management and makes it easy to trace how state changes.
Example
This demonstrates centralizing all application state in a single store with a unified update mechanism, making state changes predictable and enabling powerful debugging features like time-travel.
// Create a single store that holds all application state
const store = createStore({
user: null, // User authentication data
cart: [], // Shopping cart items
ui: { theme: 'light' } // UI preferences
});
// Update state through centralized dispatch mechanism
store.dispatch({ type: 'SET_USER', payload: user });
Benefits
- Provides single source of truth for all application state.
- Enables time-travel debugging and state persistence easily.
- Makes it simple to trace how and when state changes.
- Facilitates predictable state updates with centralized logic.
Tradeoffs
- Can become a performance bottleneck if the entire app re-renders on any state change.
- May grow unwieldy as the application scales without careful organization.
- Creates tight coupling to the store structure across the application.
- Can be overkill for applications with simple or isolated state needs.