Sub topic 10
Wrapping Context in a Provider Component and Custom Hook
This chapter assumes you know createContext, Provider and useContext. It also assumes you know useState, and that you can predict when a component re-renders. By the end you will be able to hide a context behind two exports: a provider component and a custom hook.
Why wrap a context
A bare context works, but it leaves three jobs to every caller:
- Each consumer must import both the context object and
useContext. - Whoever renders the
Providermust create the state and decide what object to pass asvalue. - Nothing warns you when a component reads the context outside any provider. It silently receives the default value.
A provider component and a custom hook fix all three. The provider owns the state. The hook is the only way to read it. The context object itself is never exported, so no one can use it incorrectly.
The pattern
The following example builds an authentication context.
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>;
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (ctx === null) {
throw new Error('useAuth must be used inside <AuthProvider>');
}
return ctx;
}The file has two exports and one private constant. Here is what each part does.
The context and its default
createContext(null) uses null as the default on purpose. A real value is always an object with user, login and logout, so null can only mean "no provider above". This is what lets the hook detect a mistake. A default like { user: null } would hide it.
The provider component
AuthProvider is an ordinary component that accepts children. It holds the useState call, so the state lives in one place. Because it takes children as a prop, you can place it high in the tree without it needing to know what it wraps.
The children prop also helps performance. When AuthProvider re-renders because user changed, the children elements were created by a parent that did not re-render. React reuses those elements and skips them unless they read the context. Only consumers of AuthContext re-render.
The memoized value
The value object is built with useMemo. Without it, each render of AuthProvider creates a new object. React compares context values with Object.is, so a new object counts as a change and every consumer re-renders, even if user is the same.
login and logout are wrapped in useCallback with empty dependency arrays. This keeps their identity stable. If they were recreated on every render, the useMemo dependency list would change every time and the memoization would do nothing. The updater setUser is stable by guarantee, so the empty arrays are correct.
The custom hook
useAuth calls useContext and checks for null. If a component calls it outside <AuthProvider>, you get an error that names the cause and the fix, instead of a later Cannot read properties of null somewhere unrelated.
Using it
import { AuthProvider, useAuth } from './auth';
function LoginButton() {
const { user, login, logout } = useAuth();
return user ? (
<button onClick={logout}>Log out {user.name}</button>
) : (
<button onClick={() => login('Ada')}>Log in</button>
);
}
function Greeting() {
const { user } = useAuth();
return <p>{user ? `Hello, ${user.name}` : 'Please log in.'}</p>;
}
export default function App() {
return (
<AuthProvider>
<Greeting />
<LoginButton />
</AuthProvider>
);
}App has no state and passes no props. Both children call useAuth() and see the same data. Clicking the button calls login, which updates state inside AuthProvider. React re-renders the provider, produces a new memoized value, and re-renders both consumers.
Choosing the default value
Two common styles exist, and each suits a different situation.
| Style | Default | Outside a provider | Use when |
|---|---|---|---|
| Required provider | `null` | Hook throws | The context has no sensible standalone value, such as auth or a data store |
| Optional provider | A complete, working value | Hook returns the default | The context is configuration with a safe fallback, such as a theme |
For the required style, throw from the hook. For the optional style, the hook can simply return useContext(Ctx) and you may not need a custom hook at all.
Edge cases and common errors
Checking the wrong thing
The check ctx === null only works if the default is exactly null. If you change the default to undefined or {}, update the check to match. Test it once by rendering a consumer without a provider and confirming that the error appears.
Forgetting to memoize
If the provider renders often for reasons unrelated to the context, such as a parent that re-renders it, an unmemoized value makes every consumer re-render each time. The code still works, so the cost shows up only as slowness. Memoize when the provider has other re-render triggers or the consumers are expensive. For a provider at the root with few updates, skipping useMemo is acceptable.
Putting unrelated state in one provider
Every consumer re-renders when any field of value changes, even if it reads only one field. Destructuring const { login } = useAuth() does not prevent that. If one provider mixes fast-changing data with stable data, split it into separate contexts. A later chapter covers splitting in detail.
Exporting the context object
Do not export AuthContext. If you do, other files can call useContext(AuthContext) directly and bypass the null check. Keep it private to the module.
Hot reload and file layout
Some tooling, such as React Fast Refresh, works best when a file exports only components. Mixing a component and a hook in one file can trigger lint warnings or force full reloads. If you see that, move the hook to a sibling file and import the context from a third file. Both options are valid. Pick one and apply it consistently.
Adding a selector-style hook
You can expose narrower hooks on top of the same context. They still cause re-renders when the whole value changes, but they make call sites clearer:
export function useUser() {
return useAuth().user;
}This does not reduce re-renders. Use it for readability, not for performance.
Summary of the pattern
- Create the context privately with
nullas the default when a provider is required. - Write a provider component that owns state and accepts
children. - Memoize the value, and stabilize any functions inside it with
useCallback. - Export a custom hook that calls
useContextand throws if the result isnull. - Export only the provider and the hook.
Exercise
A teammate removes useMemo from AuthProvider and writes value={{ user, login, logout }}. The app still behaves correctly. Why might it now be slower, and in which situation would you notice the difference?
Show answer
Each render of AuthProvider now creates a new object, and React compares context values with Object.is, so every consumer re-renders whenever the provider renders, even if user has not changed. You would notice it when the provider re-renders for other reasons, for example because its parent re-renders, and the consumers are numerous or expensive to render.
Exercise
You change createContext(null) to createContext({ user: null }) in the auth example and leave useAuth as written. A component calls useAuth() outside <AuthProvider>. What happens, and how would you restore the clear error?
Show answer
No error is thrown, because ctx is the default object and never equals null. The component receives { user: null }, and calling login fails with "login is not a function". To restore the clear error, set the default back to null (or check for a distinct sentinel value) so the hook can detect a missing provider.