π§ What Is Context?
Reactβs Context API allows you to create a global-like state that any component can accessβ without manually passing props through every level.
π‘ Step-by-Step: Using useContext for State Sharing
// 1. Create the context
import React, { createContext, useState, useContext } from "react";
const ThemeContext = createContext();
// 2. Create a provider component
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Consume context in a deeply nested child
function ThemeToggleButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Switch to {theme === "light" ? "dark" : "light"} mode
</button>
);
}
// 4. Wrap your app with the provider
function App() {
return (
<ThemeProvider>
<div>
<h1>Welcome to the App</h1>
<ThemeToggleButton />
</div>
</ThemeProvider>
);
}
export default App;
β Benefits of Using Context
- Eliminates prop drilling
- Centralizes shared state
- Works well with hooks like
useContext,useReducer, oruseMemofor optimization
π§© When to Use Context vs Redux
| Use Case | Context API | Redux / NgRx |
|---|---|---|
| Small to medium app | β Recommended | βοΈ Optional |
| Complex state logic | βοΈ Possible | β Better suited |
| Global state (theme, auth) | β Ideal | β Also works |
| DevTools, time-travel debugging | β Not available | β Built-in |
| Async side effects | β Manual setup | β Effects / Middleware |