liveBook · Manning

Multiple context

As explained in React Hooks in Action: With Suspense and Concurrent Mode

Context separation is the practice of representing independently consumed shared values with distinct React contexts.

Multiple context separates independently consumed shared values into distinct React contexts. Components call useContext only for the values they need, limiting updates to relevant consumers. section 8.2 section 8.2.3

Apply the pattern by:

  • Creating one context for each independently consumed shared value. section 8.2.3
  • Nesting providers and placing them near the subtree that consumes them. section 8.2.3
  • Grouping stable provider combinations in a custom provider when they belong together. section 8.2.3
  • Separating a state value from its updater function when consumers need different subscriptions. section 8.2.3

Independent UI consumers

An InfoPage can consume ThemeContext and LanguageContext, while Messages consumes ThemeContext and UserContext. Each component selects only the shared values it uses.

Listing 8.9 Using separate providers for a value and its updater function
import {createContext, useState} from "react";
 
const UserContext = createContext();
export default UserContext;
 
export const UserSetContext = createContext();     #1
 
export function UserProvider ({children}) {
  const [user, setUser] = useState(null);
 
  return (
    <UserContext.Provider value={user}>            #2
      <UserSetContext.Provider value={setUser}>    #3
        {children}
      </UserSetContext.Provider>
    </UserContext.Provider>
  );
}
#1 Create a separate context for setting the current user.
#2 Set the user as a value.
#3 Set the updater function as a value on its own provider.

Separate UserContext and UserSetContext providers expose the current user and its updater independently. section 8.2.3

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains provider nesting, custom grouping, and separate updater contexts, stopping short of broader context optimization.
Examples
Uses theme, user, language, and animal providers alongside InfoPage and Messages consumers.
What it assumes
Assumes familiarity with React components, Provider components, useContext, and state updater functions.
What you can do after
Apply it via the React Context API to organize shared values and reduce unrelated consumer updates.
How it connects
Connects React Context API, Provider components, useContext, custom providers, and state updater functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.