- The
useContexthook allows you to access values from React’s Context API directly inside a functional component. - Without it, you would need to pass props manually down multiple levels (prop drilling).
- It makes data sharing across deeply nested components easier (like theme, user data, language, etc.).
🔹 Steps to Use useContext()
- Create a Context
import React, { createContext } from "react";
// Step 1: Create context
export const ThemeContext = createContext();
- Provide Context Value (wrap components with
Provider)
import React, { useState } from "react";
import { ThemeContext } from "./ThemeContext";
import Child from "./Child";
function App() {
const [theme, setTheme] = useState("light");
return (
// Step 2: Provide value
<ThemeContext.Provider value={{ theme, setTheme }}>
<Child />
</ThemeContext.Provider>
);
}
export default App;
- Consume Context Value using
useContext
import React, { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function Child() {
// Step 3: Use useContext
const { theme, setTheme } = useContext(ThemeContext);
return (
<div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff" }}>
<h2>Current Theme: {theme}</h2>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Toggle Theme
</button>
</div>
);
}
export default Child;
🔹 Without useContext (Problem: Prop Drilling)
function App() {
const theme = "dark";
return <Parent theme={theme} />;
}
function Parent({ theme }) {
return <Child theme={theme} />;
}
function Child({ theme }) {
return <h2>Theme: {theme}</h2>;
}
👉 Here, theme is passed through every component level, even if intermediate components don’t use it.
With useContext, Child can directly access theme from Context. 🎯
🔹 When to Use useContext?
✅ For global data like:
- Authentication (user login info)
- Themes (dark/light mode)
- Language settings (i18n)
- App-level configuration
❌ Don’t use it for frequently changing states (like large form values) → better to use Redux/Zustand.
✅ Short Interview Answer
“The
useContexthook is used to consume values from React’s Context API directly in functional components, avoiding prop drilling. You create a Context, wrap components with itsProvider, and then access the values usinguseContext. It’s best for sharing global data like themes, user authentication, or settings.”