Sub topic 3
React useContext: Sharing State Across Components Without Prop Drilling
Assume you know JavaScript modules, JSX, function components, props, useState, and basic React re-rendering.
Memoizing the value you pass down
Context consumers re-render when the provider’s value changes. React compares the value by identity. An object created during every render is a new value, even when its contents are unchanged.
Use useMemo for the object and useCallback for functions inside it:
import { createContext, useCallback, useContext, useMemo, useState } from "react";
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = useCallback((name) => {
setUser({ name });
}, []);
const logout = useCallback(() => {
setUser(null);
}, []);
const value = useMemo(
() => ({ user, login, logout }),
[user, login, logout]
);
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
}Memoization prevents parent re-renders from creating a different context value. It does not prevent consumers from re-rendering when user changes.
Wrapping context in a provider component and custom hook
A provider component hides state-management details. A custom hook gives consumers a short API and reports configuration errors clearly:
export function useAuth() {
const context = useContext(AuthContext);
if (context === null) {
throw new Error("useAuth must be used inside <AuthProvider>");
}
return context;
}Scaling up with useReducer and context
For many related actions, put a reducer and its dispatch function in context. A reducer is a function that calculates the next state from the current state and an action. Components dispatch actions instead of changing state directly.
Splitting contexts to limit re-renders
Use separate contexts for state and dispatch, or for unrelated concerns such as theme and authentication. A component that only reads dispatch then avoids updates caused by task-list changes. Splitting also makes each context’s responsibility clearer.
When context is the wrong tool
Use props when data has a short path or only one consumer. Use component composition when a parent can pass a ready-made child instead of exposing shared state. Consider an external state library when you need selectors, persistence, complex server synchronization, or frequent updates across a large tree.
Reading context with the use API
In React 19, use can read context:
import { use } from "react";
function SaveButton() {
const auth = use(AuthContext);
return <button disabled={!auth.user}>Save</button>;
}The use API still reads the nearest provider. Unlike hooks, use may be called conditionally or in a loop.
Exercise
Why memoize an object passed to a context provider?
Show answer
To keep its identity stable when its contents have not changed, avoiding consumer re-renders caused only by a parent re-render.