Real Production State Systems
Real Production State Systems combine local UI state, shared stores, TanStack Query caches, optimistic updates, tenant isolation, and production debugging.
Course: React — State Management Lesson: 15
Learning objectives
Combine local state, shared client state, server-state caching, URL state, authentication boundaries, mutations, and observability into a production-oriented React state system.
Scenario: multi-tenant business SaaS
Imagine a platform where customers manage products, orders, inventory, campaigns, and reports. Users can belong to different workspaces and have different permissions. The interface must stay responsive while handling changing server data and unreliable networks.
Recommended responsibility map
| Requirement | Suitable owner |
|---|---|
| Modal open/closed | Component state |
| Multi-step campaign editor | Feature state / reducer |
| Current workspace | Shared client state |
| Signed-in user/session status | Auth provider or auth layer |
| Orders and products from API | Server-state layer |
| Search/filter/page in shareable views | URL state |
| Notifications | Focused shared client state |
| Form field errors | Form state |
The exact library choices depend on the existing stack and team requirements.
Example project structure
src/app/providers/router/store/features/orders/components/hooks/services/state/tests/inventory/components/hooks/services/campaigns/components/hooks/state/shared/api/auth/query/notifications/ui/
Data flow for an order list
URL query params|vOrdersPage|vuseOrders(filters, page)|vQuery cache / server-state layer|vOrder service|vBackend API|vTenant-authorized response|vCached data -> selectors/view -> rendered table
The route and query parameters represent shareable view state. The server remains authoritative for orders and access permissions.
Create and update workflows
For a create-order action:
- Validate user input.
- Check UI capability for a helpful experience.
- Submit through a mutation service.
- Prevent accidental duplicate submission.
- Display field-level validation or safe error feedback.
- Invalidate or update related query data.
- Navigate to the new order or update the current view.
- Emit an appropriate analytics event without sensitive payloads.
The backend must validate the request, enforce tenant and resource permissions, and protect operations against duplicates where needed.
Tenant and authentication lifecycle
When a user signs out or changes workspace:
- Update the active identity/workspace state.
- Cancel or isolate in-flight work where appropriate.
- Clear or scope cached user/tenant data.
- Re-fetch data under the new identity.
- Ensure the backend independently enforces tenant boundaries.
Never rely on a client-side store to prevent cross-tenant data access.
Error and offline strategy
Design consistent pending, success, empty, and failure states. Decide which views can display stale data, which mutations can be retried, and which operations require the user to reconnect. For mutations, consider idempotency and reconciliation rather than blindly replaying requests.
Production observability
Monitor:
- API latency and error rates.
- Query and mutation failure rates.
- Cache hit/refetch behavior where measurable.
- Critical workflow completion.
- Frontend exceptions and rendering performance.
- Authentication/session failures.
Use correlation identifiers to connect frontend errors with backend traces where available. Do not log credentials, tokens, payment details, or unnecessary personal data.
Testing strategy
- Unit-test reducers, store actions, selectors, and service error mapping.
- Test query hooks with controlled API responses.
- Test optimistic rollback and concurrent mutation cases.
- Test tenant switching and logout cache cleanup.
- Integration-test routes, filters, and mutations.
- End-to-end test critical business workflows.
Production readiness checklist
- Every state value has a documented owner.
- Server state is not duplicated unnecessarily in a client store.
- Query keys include all relevant filters and tenant scope.
- Cache invalidation is defined for important mutations.
- Session and workspace transitions isolate user data.
- Loading, empty, error, and success states are implemented.
- Stale requests cannot overwrite current results.
- High-risk mutations have duplicate protection.
- Backend authorization and tenant isolation are enforced.
- Sensitive data is excluded from logs.
- Performance is measured under realistic data volume.
- Critical workflows have automated tests and monitoring.
Common mistakes
- Choosing one library as the home for every state category.
- Storing API data in multiple independent caches.
- Failing to clear tenant-scoped data after a workspace switch.
- Optimistic updates without rollback or concurrency strategy.
- Treating client-side route or permission checks as security.
- Shipping without observability and workflow tests.
Interview questions & answers
Interview preparation
7 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1Design a state-management architecture for a multi-tenant SaaS.
BeginnerModel answer
Local UI state in components/feature hooks; shared client state in a focused store if needed; server state in TanStack Query/RTK Query with tenant-scoped keys; clear caches on tenant switch; backend authz always.
2How do you handle optimistic updates safely?
BeginnerModel answer
Snapshot prior cache, apply optimistic patch, rollback on failure, and reconcile with server data; avoid high-risk irreversible operations.
3What state-related metrics would you monitor?
BeginnerModel answer
Cache hit rate, refetch latency, mutation failure/rollback rate, stale UI reports, and auth/tenant switch cache-clear success.
Intermediate
4How do local state, Redux/Zustand, and TanStack Query coexist?
IntermediateModel answer
Local for ephemeral UI, Redux/Zustand for cross-feature client workflows, TanStack Query for remote cache—each with a clear ownership boundary.
5What should be invalidated after creating an order?
IntermediateModel answer
Order list/detail queries and any dependent dashboards or counts whose cache keys are affected by the new order.
Advanced
6How do you prevent cross-tenant cache leakage?
AdvancedModel answer
Include tenant identity in cache keys and wipe or partition caches on logout and tenant switch.
7How would you debug stale data in production?
AdvancedModel answer
Inspect cache keys, invalidation paths, race logs, and tenant scope; correlate mutation success with subsequent refetch behavior.
Capstone project
Build a production-style state system for an order and inventory SaaS. Include workspace selection, authentication state, URL-driven filters, server-cached order data, local editor state, a shared notification system, optimistic task updates, and tenant-aware cache lifecycle. Add unit, integration, and end-to-end tests.