What is Context in React?
Context in React is a mechanism that lets you pass data through the component tree, without using props at every level.
The problem Context solves
Normally, data in React flows top-down through props:
javascript
<App>
<Header user={user} />
</App>But if user is needed by a component deep inside the tree, you have to pass it through every intermediate component - this is called prop drilling.
Context solves this problem.
How Context works
Context lets you create a global data store (at the level of React components) that any child component can connect to, without passing props manually.
Usage example
1. Create the context
javascript
import { createContext } from "react";
export const ThemeContext = createContext("light");2. Wrap the components in a Provider
javascript
import { ThemeContext } from "./ThemeContext";
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}3. Subscribe to the context through useContext
javascript
import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Button</button>;
}Key elements
| Element | Purpose |
|---|---|
createContext(defaultValue) | Creates a context with an initial value |
<Context.Provider value={...}> | Makes the value available to all child components |
useContext(Context) | Retrieves the current context value inside a component |
Important to remember
- All components using the context will re-render if the
valuechanges. - To optimize, memoize value:
javascript
const value = useMemo(() => ({ user, setUser }), [user]);
<UserContext.Provider value={value}>...</UserContext.Provider>- Context does not replace global state managers (Redux, Zustand, etc.), but it fits well for:
- UI theme (light/dark),
- interface language,
- the current user,
- UI settings.
A simple comparison
| Approach | When to use |
|---|---|
props | Local data passed 1-2 levels down |
context | Shared data needed in many places in the app |
| state managers (Redux, Zustand) | Complex state with logic, side effects, caching, etc. |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.