React Context API (Basic State Management)
The React Context API provides a way to manage state globally and share data between components without passing props manually at every level. It helps in avoiding prop drilling and simplifies state management in React applications.
When to Use Context API?
✅ When multiple components need access to the same data.
✅ To avoid passing props manually through multiple levels (prop drilling).
✅ For managing global state such as themes, authentication, user preferences, etc.
Creating and Using Context API
To use the Context API, follow these steps:
👉 Step 1️⃣: Create Context
Define ThemeContext and ThemeProvider to store theme state.
import React, { createContext, useState } from ‘react’;
// Create a new context
export const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(“light”);
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
👉 Step 2️⃣: Provide Context in the App
Wrap the application inside the ThemeProvider to make context available globally.
import React from ‘react’;
import { ThemeProvider } from ‘./ThemeContext’;
import AppContent from ‘./AppContent’;
function App() {
return (
<ThemeProvider>
<AppContent />
</ThemeProvider>
);
}
export default App;
👉 Step 3️⃣: Consume Context in Components
Use the useContext hook to access context values in child components.
import React, { useContext } from ‘react’;
import { ThemeContext } from ‘./ThemeContext’;
function ThemeToggler() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<p>Current Theme: {theme}</p>
<button onClick={() => setTheme(theme === “light” ? “dark” : “light”)}>
Toggle Theme
</button>
</div>
);
}
export default ThemeToggler;
🎯 How It Works
✔ Global State: ThemeContext allows any component to access the theme.
✔ No Prop Drilling: No need to pass props through multiple components.
✔ Dynamic Updates: Clicking the button toggles between light and dark mode.
Context API vs Props vs Redux
Feature | Context API | Props | Redux |
---|---|---|---|
Global State Management | ✅ Yes | ❌ No | ✅ Yes |
Avoids Prop Drilling | ✅ Yes | ❌ No | ✅ Yes |
Complexity | 🔹 Moderate | 🔹 Simple | 🔸 High |
Performance Overhead | 🔹 Minimal | 🔹 None | 🔸 Higher |
Best Practices
✅ Use Context API for global state like themes, authentication, or language settings.
✅ Avoid overusing context for frequently changing states (use useState instead).
✅ Keep context logic separate in a provider file for better organization.
✅ Optimize performance using memoization (React.memo, useMemo).
Conclusion
The React Context API is a powerful way to manage global state efficiently. It eliminates prop drilling, keeps components cleaner, and improves code maintainability. Understanding Context API helps build scalable React applications with better state management!