State Management
Subject: React
π What is State Management?
In React, state refers to data that drives component behavior and UI rendering.
State Management is the technique of controlling how that data is created, updated, and shared across components.
πͺ 2. Lifting State Up
β What It Means
When multiple sibling components need access to shared state, move the state to their nearest common parent.
π¦ Example
πͺ’ 3. Prop Drilling
π What It Means
Prop Drilling is when you pass data through multiple components β even if some intermediate ones donβt use it.
π Example
Problem: Parent
has to pass down user
even if it doesn't need it.
π 4. Context API
β Why Use It?
To avoid prop drilling and make shared state accessible deep in the component tree.
π οΈ Step-by-Step
1. Create Context
2. Provide Context
3. Consume Context
π§° 5. External State Management Libraries
When your app grows, Context may become hard to manage or inefficient. That's where state libraries come in.
π Redux
β Core Features
- Centralized global store
- Actions & reducers for logic
- Middleware support (e.g., Redux Thunk)
π§ͺ Example Flow
1. Create Slice
2. Configure Store
3. Wrap in Provider
4. Use in Component
β‘ Zustand
β Features
- Minimal API (just one hook)
- No boilerplate
- Fast and simple
𧬠Recoil
β Features
- Built for React
- State via atoms
- Supports async selectors
π§ When to Use What?
Use Case | Tool/Pattern |
---|---|
Small local state | useState |
Shared state between siblings | Lifting State Up |
Avoid prop drilling | Context API |
Large-scale global state | Redux / Zustand |
Async derived state & reactivity | Recoil |
β Summary
Tool | Best For | Type | Complexity |
---|---|---|---|
useState | Local UI state | Built-in | Low |
Lifting State | Sharing state among siblings | Built-in | Low |
Context API | Avoiding prop drilling | Built-in | Medium |
Redux | Large apps with global state needs | External | High |
Zustand | Simple global state with hooks | External | Low |
Recoil | Atom-based reactivity + async data | External | Medium |
Advertisement Slot 1
Advertisement Slot 2