Multiple contexts in an application
Yes - in React you can (and often should) use several contexts at the same time. This is a completely normal and recommended practice.
Why have several contexts at all?
Context is meant for global data of one type - theme, language, user, settings, and so on. If you store everything in one context, you get a "monolith" where any change causes unnecessary re-renders.
So it is better to split contexts by area of responsibility:
| Context | Responsible for |
|---|---|
ThemeContext | The application theme (light/dark) |
AuthContext | Authorization and the user |
LangContext | The current interface language |
UIContext | Modals, notifications, layout state |
SettingsContext | User settings |
Example with several contexts
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
const UserContext = createContext({ name: "Guest" });
function App() {
return (
<ThemeContext.Provider value="dark">
<UserContext.Provider value={{ name: "Alex" }}>
<Profile />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
function Profile() {
const theme = useContext(ThemeContext);
const user = useContext(UserContext);
return (
<div className={theme}>
<h1>Hello, {user.name}!</h1>
<p>Theme: {theme}</p>
</div>
);
}Here:
Appwraps the components in two providers at once;Profilereceives both values through twouseContext()calls.
The order of the Providers does not matter,
as long as each of them wraps the components that need it.
<AuthContext.Provider value={user}>
<ThemeContext.Provider value={theme}>
<App />
</ThemeContext.Provider>
</AuthContext.Provider>or
<ThemeContext.Provider value={theme}>
<AuthContext.Provider value={user}>
<App />
</AuthContext.Provider>
</ThemeContext.Provider>Both variants work the same way.
Several contexts through <Context.Consumer>
If you work with classes or without hooks:
<ThemeContext.Consumer>
{theme => (
<UserContext.Consumer>
{user => (
<p>{user.name} uses the {theme} theme</p>
)}
</UserContext.Consumer>
)}
</ThemeContext.Consumer>But this quickly gets unwieldy - in function components useContext is always better.
Summary
You can and should use several contexts.
Each context is for its own "area of responsibility".
A component can consume as many contexts as it needs through useContext.
This improves structure, readability and performance.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.