📌 What is useContext?
🔹 What is Context in React?
Context is a feature in React that allows data sharing across components without passing props manually at every level. It is created using React.createContext() and provides a Provider-Consumer mechanism.
- Provider: Supplies the context value to the component tree.
- Consumer (useContext): Retrieves the context value wherever needed.
🔹 Why useContext?
- Avoids Prop Drilling – Eliminates the need to pass props manually at multiple levels.
- Enhances Code Readability – Makes component communication more direct and manageable.
- Centralized State Management – Useful for themes, authentication, user settings, and global state.
- Efficient Performance – Only components consuming the context re-render when the context value changes.
🔹 How useContext Works
- A Context Object is created using React.createContext().
- A Provider Component wraps the part of the component tree that needs access to the shared data.
- Components inside the provider consume the context using the useContext hook.
🔹 Basic Steps to Use useContext
- Create a Context using createContext.
- Provide the Context with Context.Provider.
- Consume the Context using useContext
🛠 Example: Theme Context (Dark/Light Mode)
1️⃣ Create a Context (ThemeContext.js)
import { ThemeProvider } from "./ThemeContext";
import ThemeSwitcher from "./ThemeSwitcher";
function App() {
return (
<ThemeProvider>
<ThemeSwitcher />
</ThemeProvider>
);
}
export default App;
3️⃣ Consume the Context (ThemeSwitcher.js)
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function ThemeSwitcher() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff", padding: "20px" }}>
<h2>Current Theme: {theme}</h2>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
}
export default ThemeSwitcher;
📌 Summary
- createContext() → Creates a context.
- Context.Provider → Provides the data to child components.
- useContext(Context) → Allows child components to access the data.
0 Comments