05 State Management
Jab application badi hoti hai, to sabse badi problem hoti hai Data (State) ko manage karna.
1. The Problem: Prop Drilling 😫
Agar Grandparent component se Grandchild ko data bhejna ho, to Parent ke through paas karna padta hai, bhale hi Parent ko uski zaroorat na ho. Isse Prop Drilling kehte hain.
Solution: State Management Tools (Context API ya Redux).
2. Context API (Built-in Solution) 💡
Chhoti aur medium apps ke liye best hai. Ye data ko “Teleport” kar deta hai.
Step 1: Context Create karo (UserContext.js)
import { createContext } from 'react';export const UserContext = createContext();Step 2: Provider se Wrap karo (App.js)
import { UserContext } from './UserContext';
function App() { const user = { name: "Aditya", role: "Dev" };
return ( <UserContext.Provider value={user}> <Profile /> </UserContext.Provider> );}Step 3: Data Use karo (Profile.js)
useContext hook ka use karke direct data milega!
import { useContext } from 'react';import { UserContext } from './UserContext';
function Profile() { const user = useContext(UserContext); return <h1>Hello {user.name}</h1>;}3. Redux Toolkit (For Heavy Apps) 🛠️
Jab app bahut complex ho (E-commerce, Dashboard), tab Redux Toolkit (RTK) use karein.
Key Concepts:
- Store: Ek bada dabba jahan sara data rehta hai.
- Slice: Dabbe ke chote parts (UserSlice, CartSlice).
- Reducer: Functions jo data change karte hain.
- Dispatch: Action fire karna (e.g., “Add to Cart”).
- Selector: Data nikalna.
Example (Counter)
1. Slice Banao (counterSlice.js)
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({ name: 'counter', initialState: { value: 0 }, reducers: { increment: state => { state.value += 1 }, decrement: state => { state.value -= 1 }, }});
export const { increment, decrement } = counterSlice.actions;export default counterSlice.reducer;2. Component me Use Karo
import { useSelector, useDispatch } from 'react-redux';import { increment } from './counterSlice';
function Counter() { const count = useSelector(state => state.counter.value); // Read const dispatch = useDispatch(); // Write
return ( <div> <h1>Count: {count}</h1> <button onClick={() => dispatch(increment())}>+</button> </div> );}4. Kab Kya Use Karein? 🤔
| Feature | Context API | Redux Toolkit |
|---|---|---|
| Complexity | Easy | Medium/Hard |
| Setup | Built-in | Install karna padega |
| Performance | Thoda slow (Re-renders) | Highly Optimized |
| Best For | Theme, User Auth | E-commerce Cart, Complex State |
Summary
State Management ka matlab hai data ko sahi jagah pahunchana.
- Context API: Easy, choti apps ke liye.
- Redux Toolkit: Powerful, badi apps ke liye.
🎉 Mubarak ho! Ab aap React ke “Hero” ban chuke hain. Components, API, Routing, aur State sabkuch aapke control me hai!