Skip to main content

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:

ContextResponsible for
ThemeContextThe application theme (light/dark)
AuthContextAuthorization and the user
LangContextThe current interface language
UIContextModals, notifications, layout state
SettingsContextUser settings

Example with several contexts

javascript
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:

  • App wraps the components in two providers at once;
  • Profile receives both values through two useContext() calls.

The order of the Providers does not matter,

as long as each of them wraps the components that need it.

javascript
<AuthContext.Provider value={user}> <ThemeContext.Provider value={theme}> <App /> </ThemeContext.Provider> </AuthContext.Provider>

or

javascript
<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:

javascript
<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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.