Day 95 State Management
Complex apps mein state ko multiple components share karna hota hai. Context API + useReducer React built-in solution hai — Redux ki zaroorat nahi chhoti apps mein.
Context API + useReducer
Global state management.
import { createContext, useContext, useReducer } from "react";
// State shape
const initialState = {
user: null,
cart: [],
theme: "dark",
notifications: []
};
// Reducer — pure function
function appReducer(state, action) {
switch (action.type) {
case "SET_USER":
return { ...state, user: action.payload };
case "ADD_TO_CART":
const exists = state.cart.find(i => i.id === action.payload.id);
return {
...state,
cart: exists
? state.cart.map(i => i.id === action.payload.id ? { ...i, qty: i.qty + 1 } : i)
: [...state.cart, { ...action.payload, qty: 1 }]
};
case "REMOVE_FROM_CART":
return { ...state, cart: state.cart.filter(i => i.id !== action.payload) };
case "TOGGLE_THEME":
return { ...state, theme: state.theme === "dark" ? "light" : "dark" };
default: return state;
}
}
// Context create
const AppContext = createContext();
export function AppProvider({ children }) {
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
}
// Custom hook
export function useApp() {
return useContext(AppContext);
}
// Usage in any component
function CartButton() {
const { state, dispatch } = useApp();
return (
<button onClick={() => dispatch({ type: "TOGGLE_THEME" })}>
Cart ({state.cart.length}) — {state.theme} mode
</button>
);
}
🎯 Practice Challenge
E-commerce app mein global cart state Context + useReducer se manage karo. Cart count header mein dikhao.