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
