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 have seen useState and why a new object on each render is a new value. Here you package those pieces into a reusable unit.
The problem with raw context
Using a context directly spreads setup across the app. Every App that needs auth has to:
- Own the state and the functions that change it.
- Build the value object and render
<AuthContext.Provider>. - Import the context object in every consumer and call
useContext(AuthContext).
Consumers also get no help when they forget the provider. With a default of null, they get a confusing Cannot read properties of null error far from the real mistake.
The pattern: one provider component, one hook
Put the state, the provider and the reader in one module. Export only two things: a provider component and a hook. Keep the context object private.
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;
}Three details matter here.
- State lives inside the provider.
Appno longer knows how auth works. It only renders<AuthProvider>. - The value is memoized.
useMemoreturns the same object untiluser,loginorlogoutchanges. Without it, any re-render ofAuthProvidercreates a new object, and every consumer re-renders even if nothing changed.useCallbackkeeps the two functions stable so they do not invalidate the memo. - The hook guards against misuse. The default is
nullon purpose. If a component callsuseAuth()outside the provider, it fails immediately with a message that names the fix.
Using it
Consumers import only the hook. They never see AuthContext.
import { AuthProvider, useAuth } from './auth';
function Profile() {
const { user, login, logout } = useAuth();
if (user === null) {
return <button onClick={() => login('Ada')}>Log in</button>;
}
return (
<div>
<p>Hello, {user.name}</p>
<button onClick={logout}>Log out</button>
</div>
);
}
export default function App() {
return (
<AuthProvider>
<Profile />
</AuthProvider>
);
}Why this structure helps
- A smaller public surface. You can change the value's shape, or switch from
useStatetouseReducer, without touching consumers. - Fewer imports and typos. Consumers write
useAuth()instead of pairinguseContextwith the right context object. - Clearer failures. A missing provider produces one specific error.
- Easy testing. A test wraps the component in
<AuthProvider>, or in a small fake provider for the same context.
Common errors
- Using
undefinedornulldefaults with a real value. The guardctx === nullonly works ifnullis never a legitimate value. Here the value is always an object, so it is safe. - Skipping the memo. The code still works, but every provider re-render triggers consumer re-renders. This shows up only as slowness.
- Exporting the context object. Once consumers import it, they can bypass the guard and the pattern erodes.
- Putting the provider too low. Every consumer must be a descendant of the provider. Place it at the lowest common ancestor, often near the root.
Exercise
A teammate calls useAuth() in a component that is rendered outside <AuthProvider>. What happens, and why does the guard ctx === null work in this example?
Show answer
The hook throws useAuth must be used inside <AuthProvider>. Outside a provider, useContext returns the default value, which is null. A real provider always supplies an object, so null can only mean the provider is missing.