Design a scalable state management architecture comparing Redux Toolkit and Zustand with patterns for server state, client state, persistence, and performance optimization.
You are a frontend state management architect who has designed state systems for complex applications with real-time updates, offline support, and multi-tab synchronization. Create a comprehensive state management architecture for the following project. Project Details: Application Type: [SAAS DASHBOARD/E-COMMERCE/SOCIAL PLATFORM/REAL-TIME APP/CRM] Framework: [REACT/NEXT.JS/REACT NATIVE] Current State Solution: [NONE/REDUX/CONTEXT API/ZUSTAND/MIGRATING] Server State Library: [REACT QUERY/SWR/TRPC/APOLLO/NONE] Real-Time Requirements: [NONE/WEBSOCKET UPDATES/LIVE COLLABORATION] Offline Support: [NOT NEEDED/BASIC CACHING/FULL OFFLINE MODE] Section 1 - State Classification and Architecture: Define the state taxonomy separating server state that originates from API responses from client state that exists only in the browser and from URL state that represents the current navigation and filter context. Establish the decision framework for choosing where each piece of state should live including when to use the server state library cache as the single source of truth, when local component state with useState is sufficient, when global client state via Redux or Zustand is necessary, and when URL search parameters should own the state. Create the state flow diagram showing how data moves from API responses through the server state cache into component props and how user interactions create client state changes that trigger API mutations and cache updates. Specify the naming conventions for state slices, actions, selectors, and hooks that the team must follow for consistency. Address the anti-patterns to avoid including duplicating server state in client state stores, using global state for form state that should be local, and creating god stores that contain unrelated state slices. Section 2 - Redux Toolkit Implementation Pattern: Design the Redux store structure using Redux Toolkit with createSlice for each domain area organizing slices into feature folders alongside their selectors, thunks, and tests. Define the RTK Query setup for server state management including API slice definition with endpoints, tag-based cache invalidation, optimistic updates for mutation responses, and polling intervals for real-time data. Create the selector architecture using createSelector for memoized derived state with patterns for parameterized selectors that accept arguments and compound selectors that combine data from multiple slices. Specify the middleware configuration including the default serialization checker, custom middleware for logging or analytics, and the listener middleware for handling complex async workflows that replace the need for redux-saga or redux-observable. Address the code splitting strategy for Redux including how to use lazy-loaded slice injection so that reducers for feature routes are only loaded when the user navigates to that feature. Section 3 - Zustand Implementation Pattern: Design the Zustand store architecture using the slice pattern to organize related state and actions into logical groups while maintaining a flat store structure that avoids deeply nested state. Define the store creation approach comparing the simple create function with the more structured createStore pattern and when to use vanilla stores versus React-bound stores. Create the middleware composition stack including persist for local storage synchronization, devtools for Redux DevTools integration, immer for immutable state updates with mutable syntax, and subscribeWithSelector for granular subscription control. Specify the selector optimization approach using shallow equality comparisons and individual property selectors to prevent unnecessary re-renders when unrelated state changes. Address the patterns for Zustand-specific capabilities including transient updates using the set function outside React components, using getState for reading state in callbacks without subscribing, and the temporal pattern for undo/redo functionality. Section 4 - Server State Integration: Define the integration architecture between the client state manager and the server state library ensuring clear boundaries where the server state library owns all API data and the client state manager owns UI preferences, draft state, and ephemeral interaction state. Create the optimistic update pattern where user actions immediately update the UI through the client state while the server mutation runs in the background with automatic rollback on failure. Establish the cache synchronization strategy for WebSocket events that update server data including how to merge real-time updates into the query cache without triggering full refetches. Specify the data transformation layer that normalizes API responses into the shape components need, deciding whether transformations happen in the server state library via transform options or in selectors within the client state layer. Address the loading and error state management pattern that coordinates between server state loading indicators and client state UI flags to present a unified loading experience. Section 5 - Persistence and Cross-Tab Synchronization: Design the state persistence strategy specifying which state slices should persist to localStorage, sessionStorage, or IndexedDB based on their lifetime requirements and size constraints. Define the persistence middleware configuration including serialization of complex types like dates and sets, version migration functions for handling schema changes between app versions, and selective persistence that excludes ephemeral state from storage. Create the cross-tab synchronization system using the BroadcastChannel API or storage events to keep state consistent when users have multiple tabs open including conflict resolution when different tabs modify the same state simultaneously. Specify the hydration strategy for restoring persisted state on application load including how to handle stale persisted data that conflicts with fresh server data and how to show loading states during rehydration. Address the storage quota management approach including monitoring storage usage, implementing eviction policies for cached data, and gracefully handling storage full errors. Section 6 - Performance Monitoring and Debugging: Define the re-render tracking approach using React DevTools Profiler, why-did-you-render library, or custom render counting hooks to identify components that re-render excessively due to state changes. Specify the Redux DevTools or Zustand DevTools integration for state change debugging including time-travel debugging, action filtering, and state diff visualization. Create the performance optimization checklist including ensuring selectors are properly memoized, verifying that components subscribe to the minimum necessary state slice, confirming that large lists use virtualization, and checking that expensive computations are wrapped in useMemo. Design the state size monitoring approach that tracks the total size of the client state store over time and alerts when it grows beyond acceptable thresholds indicating potential memory leaks. Address the testing strategy for state management including unit testing reducers and actions in isolation, integration testing store behavior with multiple dispatches, and testing component interactions with mocked stores.
Or press ⌘C to copy