Overview
State management refers to the process of managing the data (state) of your application across components — how it’s created, updated, and shared.
There are multiple ways to manage state in React, from simple local state using useState
, to complex solutions using libraries like Redux, Zustand, etc.
1. Lifting State Up
When two or more child components need to share the same piece of state, it’s best to move that state up to their closest common parent.
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<Display count={count} />
<IncrementButton setCount={setCount} />
</>
);
}
Key Point:
Keep state as close as possible to where it’s used, but lift it up when multiple components need access.
2. Prop Drilling
Prop drilling occurs when you pass data through many intermediate components that don’t use the data, just to get it to a deeply nested child.
<Parent>
<Child1>
<Child2>
<Child3 someProp={value} />
</Child2>
</Child1>
</Parent>
Problem: Code becomes harder to read, maintain, and refactor.
Solution: Use Context API or state libraries like Redux or Zustand to avoid deep prop drilling.
3. React Context API
React Context provides a way to pass data globally to components without prop drilling.
// Create context
const ThemeContext = React.createContext();
// Wrap in a Provider
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
// Consume context
const theme = useContext(ThemeContext);
Key Point:
Great for global, rarely changing state (e.g., theme, language, auth).
Not ideal for frequently updated data — can cause unnecessary re-renders.
4. Comparing State Management Techniques
Approach | When to Use | Pros | Cons |
---|---|---|---|
useState (Local) | Simple component-level state | Easy, built-in | Not shareable across components |
Lifting State Up | Share state between siblings | Easy to implement | Can cause prop drilling |
Context API | Global, rarely-changing state | Avoids prop drilling | Can cause performance issues |
Redux | Large-scale apps with complex data flow | Centralized control, time-travel debugging | Boilerplate, harder setup |
Zustand / Recoil / Jotai | Mid-size apps or when Redux is too much | Simple API, lightweight | Still requires external libraries |
5. Popular State Management Libraries
Library | Key Features | Use Case |
---|---|---|
Redux | Predictable, central store, middleware | Complex enterprise apps |
Zustand | Minimal setup, no boilerplate | Simple to medium apps |
Recoil | Atom-based, React tree friendly | Data dependencies and interrelations |
Jotai | Atomic state, intuitive API | Modular shared state |
MobX | Reactive state, less boilerplate | Quick, automatic updates with less config |
Key Takeaways
Choose the right state management tool based on your app’s complexity and scale.
Avoid overengineering: don’t use Redux for a simple to-do list.
For most apps: useState
, useContext
, and maybe Zustand are sufficient.
Để lại một bình luận