What problems does Context solve?
1. The prop drilling problem
When you need to pass the same value (for example, user, theme, lang) deep into the component tree, you have to pass it through every level manually, even if intermediate components do not need it.
Without Context:
javascript
function App() {
const user = { name: "Tim" };
return <Layout user={user} />;
}
function Layout({ user }) {
return <Header user={user} />;
}
function Header({ user }) {
return <UserMenu user={user} />;
}
function UserMenu({ user }) {
return <p>Hello, {user.name}</p>;
}Downsides:
- a bunch of components have to "pierce through"
usereven though they do not need it; - if the structure changes, you need to change props everywhere;
- the code becomes noisy and hard to maintain.
2. How Context solves this
Context lets you create a global data source that can be accessed from anywhere in the tree without props.
javascript
const UserContext = createContext();
function App() {
const user = { name: "Tim" };
return (
<UserContext.Provider value={user}>
<Layout />
</UserContext.Provider>
);
}
function UserMenu() {
const user = useContext(UserContext);
return <p>Hello, {user.name}</p>;
}Now UserMenu takes user directly from the context, without intermediaries.
3. Typical scenarios where Context is useful
| Problem | Solution via Context |
|---|---|
| Passing the visual theme (dark/light) | ThemeContext |
| UI language / localization | LanguageContext |
| The current user (auth) | AuthContext |
| Application settings / config | SettingsContext |
| Global UI data (for example, modals, notifications) | UIContext |
4. What Context does not solve
- It is not meant for complex state, logic, or asynchronous data.
- It is not optimized for frequent state updates (every change to the value re-renders all consumers). In such cases it is better to use Redux, Zustand, Jotai, Recoil, etc.
Summary
Context solves:
- The "prop drilling" problem, it gets rid of unnecessary props passing.
- It lets you store shared data centrally.
- It makes the code cleaner and easier to maintain.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.