Machine Coding · Lesson 12 of 12 · 4 min
Complex State Management & Architecture
This is how you justify your design choices for a large application in a system design interview.
When an interviewer asks you to design a complex feature like a collaborative editor or a real-time dashboard, they're not just testing your component-building skills. They're testing your ability to architect a system that can scale without collapsing into a mess of bugs and performance issues. Your answer needs to go beyond "I'd use useState."
First, separate server state from client state
This is the single most important distinction to make. Candidates who mix them up signal a lack of experience with real-world applications.
Client state is what the user is doing right now. Is a modal open? What's the text in the input field? Is a dropdown active? This state is ephemeral, simple, and lives entirely in the browser. useState is often enough.
Server state is a cached copy of data that lives on your backend. Product lists, user profiles, dashboard data. This state is asynchronous, shared across users, and can become stale. Managing it involves caching, deduplicating requests, and invalidation.
The trap: Using useState or Redux to manage server data. You'll end up manually writing complex effects to handle loading, errors, refetching, and caching. This is a solved problem.
In an interview, your first move should be to identify the server state and declare you'll use a dedicated library for it. Name-drop React Query (or TanStack Query) or SWR. Explain why: they handle caching, background refetching, and request deduplication out of the box, which simplifies your application code immensely. This immediately shows you understand the problem domain.
Choose a client state pattern based on trade-offs
Once you've isolated client state, you still need to manage it. The choice of tool depends on the specific problem's constraints. There is no single "best" solution.
useReducer + Context: This is your scalable baseline. It keeps state updates predictable by centralizing logic in a reducer function. It's a built-in React solution for when useState becomes unwieldy with complex, related state transitions.
Unidirectional Flow (Redux): Use this when you need a single global state with robust debugging tools (like time-travel) and a rich middleware ecosystem (for logging, handling side effects, etc.). The cost is boilerplate. Don't propose Redux for a simple feature; justify it for an app with complex, cross-cutting state that many distant components need to share.
Atomic State (Jotai/Recoil): This pattern excels when you have many small, independent pieces of state that can be shared. Components subscribe only to the "atoms" they need, which minimizes re-renders automatically. It's a strong choice for highly interactive UIs like a canvas editor or a complex dashboard where performance is critical and global re-renders are unacceptable.
State Machines (XState): Reach for a state machine when you have a component with a complex, explicit lifecycle and you must prevent impossible states. Think multi-step forms, drag-and-drop interactions, or video player controls. By defining all possible states and valid transitions, you make your logic self-documenting and virtually bug-free regarding state transitions.
Model state transitions, not just state values
As state logic grows, the problem isn't the state itself, but managing the transitions between states. A boolean isLoading flag doesn't tell you what happened if it's false. Did the request succeed or fail?
Using a reducer forces you to model state as a cohesive object and transitions as explicit actions. This makes your logic easier to reason about, test, and debug.
This useReducer hook manages the state for a data-fetching operation. Notice how each state (loading, success, error) is explicit. You can't accidentally be in both a success and error state.
import { useReducer } from 'react';
const fetchReducer = (state, action) => {
switch (action.type) {
case 'FETCH_INIT':
return { status: 'loading', data: null, error: null };
case 'FETCH_SUCCESS':
return { status: 'success', data: action.payload, error: null };
case 'FETCH_FAILURE':
return { status: 'error', data: null, error: action.payload };
default:
throw new Error(`Unhandled action type: ${action.type}`);
}
};
const useApi = (url) => {
const [state, dispatch] = useReducer(fetchReducer, {
status: 'idle',
data: null,
error: null,
});
// ... effect to fetch data and dispatch actions ...
return state;
};
This is a small-scale state machine. It's more robust than managing three separate useState hooks for data, loading, and error.
Structure the application, not just the state
How you organize your files and modules is an architectural decision. For a large application, this matters as much as your state management library.
The two dominant approaches are organizing by type versus organizing by feature.
- By Type:
components/,hooks/,utils/. This is common but scales poorly. To understand or change a single feature (e.g., "user profile"), you have to jump between many folders. It encourages coupling because files are organized by their technical role, not their business purpose. - By Feature (Feature-Sliced Design):
features/user-profile/,features/search/,features/cart/. Each folder is a self-contained module with its own components, hooks, and state logic. This is harder to set up but scales far better for large teams and complex codebases because it enforces boundaries and makes code easier to find, change, and delete.
Mentioning that you'd structure the application by feature shows you're thinking about long-term maintainability and team collaboration, which are key concerns for a senior role.
Try it
Open a blank file. Sketch out the state shape and reducer actions for a multi-step checkout form (shipping, billing, payment, review). Don't write any UI code. Just define the state object and the list of possible actions, like SET_SHIPPING_INFO, VALIDATE_STEP_SUCCESS, GO_TO_NEXT_STEP. This takes 15 minutes and forces you to think purely in terms of state architecture.
Next: You've completed the course. It's time to apply these patterns in a full mock interview.
Lock it in — apply this lesson under interview conditions.