React Tutorial 0/120 lessons ~6 min read Lesson 75

    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 progress0%
    Focus
    14 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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.

    RequirementSuitable owner
    Modal open/closedComponent state
    Multi-step campaign editorFeature state / reducer
    Current workspaceShared client state
    Signed-in user/session statusAuth provider or auth layer
    Orders and products from APIServer-state layer
    Search/filter/page in shareable viewsURL state
    NotificationsFocused shared client state
    Form field errorsForm state

    The exact library choices depend on the existing stack and team requirements.

    Example project structure

    text
    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

    text
    URL query params
    |
    v
    OrdersPage
    |
    v
    useOrders(filters, page)
    |
    v
    Query cache / server-state layer
    |
    v
    Order service
    |
    v
    Backend API
    |
    v
    Tenant-authorized response
    |
    v
    Cached 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:

    1. Validate user input.
    2. Check UI capability for a helpful experience.
    3. Submit through a mutation service.
    4. Prevent accidental duplicate submission.
    5. Display field-level validation or safe error feedback.
    6. Invalidate or update related query data.
    7. Navigate to the new order or update the current view.
    8. 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

    3
    1. 1Design a state-management architecture for a multi-tenant SaaS.
      Beginner

      Model 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.

    2. 2How do you handle optimistic updates safely?
      Beginner

      Model answer

      Snapshot prior cache, apply optimistic patch, rollback on failure, and reconcile with server data; avoid high-risk irreversible operations.

    3. 3What state-related metrics would you monitor?
      Beginner

      Model answer

      Cache hit rate, refetch latency, mutation failure/rollback rate, stale UI reports, and auth/tenant switch cache-clear success.

    Intermediate

    2
    1. 4How do local state, Redux/Zustand, and TanStack Query coexist?
      Intermediate

      Model answer

      Local for ephemeral UI, Redux/Zustand for cross-feature client workflows, TanStack Query for remote cache—each with a clear ownership boundary.

    2. 5What should be invalidated after creating an order?
      Intermediate

      Model answer

      Order list/detail queries and any dependent dashboards or counts whose cache keys are affected by the new order.

    Advanced

    2
    1. 6How do you prevent cross-tenant cache leakage?
      Advanced

      Model answer

      Include tenant identity in cache keys and wipe or partition caches on logout and tenant switch.

    2. 7How would you debug stale data in production?
      Advanced

      Model 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.

    Ready to mark this lesson complete?Track your journey across the entire course.