Part 09 / Topic 3 of 6
Context plus state at the Provider
Context by itself only answers "how does a value reach far away?" - the state that value is built from still has to live somewhere, and that somewhere is the component that renders the Provider. examples/03_context_plus_state_at_provider.jsx's AuthProvider owns a real useState call and hands the value and the functions that change it down together:
// examples/03_context_plus_state_at_provider.jsx
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
function login(name) { setUser({ name }); }
function logout() { setUser(null); }
return <AuthContext.Provider value={{ user, login, logout }}>{children}</AuthContext.Provider>;
}
AccountMenu and GreetingBanner are unrelated siblings, each calling useContext(AuthContext) independently - neither one is an ancestor or descendant of the other. Clicking AccountMenu's "Log in as Asha" button really updates both of them in one go (examples/03_context_plus_state_at_provider.test.jsx): AccountMenu switches to "Logged in as Asha" and, with no prop connecting the two anywhere, GreetingBanner switches to "Welcome back, Asha!" at the exact same moment - one setUser call, one source of truth, read from two places that have never heard of each other.
Done here? The practice set for Part 9 — including the solutions — is on the part page.