Frontend System Design · Lesson 5 of 15 · 4 min
State Management Basics & Data Flow
This is where you show you can think about architecture, not just components.
Where should this state live?
This is the first question you must answer for any piece of data in your app. Get it right, and your app is easier to reason about. Get it wrong, and you create a mess.
There are three places state can live:
- Local State: The default. Data used by only one component and its direct children. A form input's value, whether a dropdown is open. Keep state as local as possible for as long as possible.
- Global State: Data needed by multiple, distant components across the app. The logged-in user, the current theme, the contents of a shopping cart.
- Server Cache State: Data that lives on a server and you're just borrowing. A list of products, a user's profile information. This is a special kind of global state that needs to handle fetching, caching, and synchronization.
The trap: New developers often reach for a global solution immediately. Don't. Start local. Only "lift state up" to a shared parent or a global store when multiple components actually need to share it. An interviewer wants to see that you understand this trade-off, not that you know how to use Redux for a simple toggle.
The default: Local state
For state that doesn't need to be shared, use the tools your framework gives you. In React, this is the useState hook.
This state is tied to the component instance. If you render two Counter components, they each have their own independent count. It's simple, predictable, and has no impact on the performance of other parts of your app.
import React, { useState } from 'react';
function CharacterCounter() {
const [inputValue, setInputValue] = useState('');
const MAX_CHARS = 20;
const charsLeft = MAX_CHARS - inputValue.length;
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={handleChange}
maxLength={MAX_CHARS}
/>
<p>Characters remaining: {charsLeft}</p>
</div>
);
}
When you update state, you must do so immutably. Never modify an existing state object or array directly.
- Wrong:
user.name = 'new name'; setUser(user); - Right:
setUser({ ...user, name: 'new name' });
Frameworks like React rely on a change in the object's reference to detect an update and trigger a re-render. Direct mutation won't create a new reference, so your UI won't update.
When local state breaks down: Prop drilling
You have state in a top-level component, but a deeply nested child needs it. The naive solution is to pass the data down as props through every intermediate component.
This is "prop drilling."
The intermediate components don't use the props; they just act as conduits. This is bad because it couples components that shouldn't know about each other. Refactoring becomes a nightmare—if you move a component, you have to rewire the entire prop chain.
In an interview, you might be asked: "You have user data in your
Appcomponent. AProfileAvatarcomponent, five levels deep in the tree, needs the user's name. How do you get it there without prop drilling?"
Your answer should involve a global state mechanism. The simplest one is built into the framework.
The first solution for shared state: Context
React's Context API is the built-in solution for prop drilling. It lets you create a "provider" that makes data available to any component in the tree below it, without passing props.
Use it for low-frequency updates of truly global data:
- Theme (dark/light mode)
- User authentication status
- Language preference
Here's how you'd provide a theme to an entire app.
import React, { useState, useContext, createContext, ReactNode } from 'react';
// 1. Define the shape of the context data
type Theme = 'light' | 'dark';
const ThemeContext = createContext<{ theme: Theme; toggleTheme: () => void; } | undefined>(undefined);
// 2. Create a provider component that holds the state
function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>('light');
const toggleTheme = () => {
setTheme(current => (current === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Create a consumer component
function ThemedButton() {
const context = useContext(ThemeContext);
if (!context) throw new Error('ThemedButton must be used within a ThemeProvider');
const { theme, toggleTheme } = context;
const style = {
background: theme === 'light' ? '#fff' : '#333',
color: theme === 'light' ? '#333' : '#fff',
border: '1px solid',
padding: '10px 20px',
};
return <button style={style} onClick={toggleTheme}>Toggle Theme</button>;
}
// 4. Wrap the app (or a part of it) in the provider
function App() {
return (
<ThemeProvider>
<h1>My App</h1>
<ThemedButton />
</ThemeProvider>
);
}
The trap: Using Context for high-frequency updates. When a context's value changes, every component that consumes it re-renders. If you put something that changes often (like a form's state or mouse coordinates) into context, you can create serious performance problems. This limitation is why dedicated state management libraries exist, which we'll cover in the next lesson.
Explain the data flow
Whether your state is local or global, modern frontend frameworks follow a predictable pattern: unidirectional data flow.
This means data moves in a single, predictable loop. You can always trace a change back to the action that caused it.
In an interview, being able to draw this on a whiteboard and walk through it is a strong signal.
- State determines what the UI looks like. The view is a function of the state.
- An Action (like a user click) is the only thing that can trigger a state change.
- The state update logic changes the State.
- The framework detects the state change and re-renders the UI.
This loop makes applications easier to debug. You don't have random parts of the UI updating other random parts. The flow is always the same.
Try it
Build a component with a text input and a character counter below it. The counter should turn red when the text exceeds 20 characters. Manage all state locally with useState. This should take about 15 minutes.
Next: Learn when Context isn't enough and how to manage complex application state in Advanced State Management & Global Stores.
Lock it in — apply this lesson under interview conditions.