React · Lesson 4
Context & custom hooks
Sharing values without prop drilling and what context costs in re-renders, custom hooks as reusable logic, composition patterns (children, render props, compound components), external stores with useSyncExternalStore, and when Zustand or Redux Toolkit is the better tool.
In short
- Context reads the nearest provider, at any depth
- A changed
valuere-renders every consumer - Memoize provider values; split fast and slow contexts
- Custom hooks share logic, never state
getSnapshotmust return a stable value
Once state is lifted to a common parent, it often has to travel through five components that don't care about it, just to reach the one that does. That's prop drilling, and React has several answers: context to make a value available to a whole subtree, custom hooks to package logic so any component can reuse it, composition to avoid the drilling in the first place, and external stores for app-wide state that changes often.
Picking the right one is a daily decision on a React team, and the wrong pick shows up as either boilerplate or a slow app that re-renders everything on every keystroke. This lesson covers how each tool works, what it costs, and when to use it.
Context
import { createContext, useContext, useState } from 'react';
type Theme = 'light' | 'dark';
const ThemeContext = createContext<Theme>('light'); // the default, used when there's no provider above
export function App() {
const [theme, setTheme] = useState<Theme>('dark');
return (
<ThemeContext value={theme}> {/* React 19; before that: <ThemeContext.Provider value={theme}> */}
<Toolbar onToggle={() => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))} />
</ThemeContext>
);
}
function ThemedButton({ label }: { label: string }) {
const theme = useContext(ThemeContext); // the nearest provider above, at any depth
return <button className={`btn btn-${theme}`}>{label}</button>;
}
- A component reads the value of the nearest provider above it. Providers can be nested and overridden for part of the tree (a dark sidebar inside a light page).
- The default from
createContextis used only when there is no provider above. A provider withvalue={undefined}providesundefined, not the default. - React 19's
use(ThemeContext)reads context too, and unlike hooks it may be called inside anif. - For context that has no sensible default (the signed-in user, a store), type it as
T | nulland wrap it in a hook that throws a clear error outside the provider. The TypeScript track's React & Angular patterns topic shows thatuseAuth()pattern.
Under the hood, React keeps a stack of values per context while it renders: entering a provider pushes its value, leaving
it pops, and useContext reads the top. Exercise 1 builds that stack.
What context costs
Context has one re-render rule: when a provider's value changes (by Object.is), every component that reads that context
re-renders, wherever it is and even if it's wrapped in memo. Two consequences catch everyone:
import { createContext, useMemo, useState, type ReactNode } from 'react';
type Auth = { user: User | null; signIn: () => Promise<void>; signOut: () => void };
const AuthContext = createContext<Auth | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
// ✗ value={{ user, signIn, signOut }} would be a new object on every render of AuthProvider,
// so every consumer would re-render whenever AuthProvider does, even if `user` didn't change.
const value = useMemo<Auth>(
() => ({ user, signIn: async () => setUser(await api.signIn()), signOut: () => setUser(null) }),
[user],
);
return <AuthContext value={value}>{children}</AuthContext>;
}
- Memoize object values. An inline
value={{ ... }}is new on every render, so every consumer re-renders whenever the provider's component does.useMemokeeps the same object until the data actually changes. If the project uses the React Compiler, it adds that memoization for you and the inline object is fine; without it, write theuseMemo. - Consumers can't pick a slice. A component that only needs
signOutstill re-renders whenuserchanges. Split contexts that change at different rates (UserContextandAuthActionsContext, orStateContextandDispatchContextfor a reducer, sincedispatchnever changes).
And one thing that makes context cheaper than it looks: children passed into a provider component aren't re-rendered by it.
In <AuthProvider><App /></AuthProvider>, the <App /> element was created by AuthProvider's parent. When AuthProvider's
state changes, React re-renders AuthProvider and the context's consumers, not the whole App. Exercise 3 builds the
"who re-renders?" rules.
Context is a transport, not a state manager: it has no selectors and no batching beyond React's own. It's ideal for values that change rarely (theme, locale, the signed-in user, feature flags, a service client). For state that changes often and is read in many places, use an external store with selectors (below).
Custom hooks
A custom hook is a function whose name starts with use and that calls other hooks. It shares logic, never state: every
component that calls it gets its own state, in its own hook slots.
import { useEffect, useState } from 'react';
export function useDebouncedValue<T>(value: T, delayMs = 300): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}
function ProductSearch() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebouncedValue(query); // only changes 300 ms after typing stops
const results = useProductSearch(debouncedQuery); // another custom hook, e.g. built on TanStack Query
return <SearchBox value={query} onChange={setQuery} results={results} />;
}
- Name it
use..., so the lint rules check that it's only called at the top level, and other developers know it holds state. - Keep the logic pure where you can. Put calculations in plain functions (
getPagination(total, page, size)) and let the hook be a thin layer ofuseStateanduseMemoaround them. Plain functions are easy to test, and exercise 2 is one. - Return what callers need: a value, a tuple (
as const, see the TypeScript track) or an object. If callers put the result in dependency arrays, keep its identity stable withuseMemo/useCallback(or let the React Compiler do it). - Test hooks with
renderHookfrom React Testing Library, or test their pure parts directly. - Don't hide everything in hooks: a hook that's used once and wraps one
useStateis just indirection.
Composition patterns
Before reaching for context, check whether composition removes the need:
childrenand slots. IfPagepassesuserdown only so thatAvatarcan use it, let the caller build<Avatar user={user} />and pass it intoPageas a slot prop (Components & props topic). No drilling and no context.- Render props. A prop that is a function returning UI lets a component own the behaviour while the caller owns the markup:
<VirtualList items={rows} renderItem={(row) => <Row row={row} />} />. Hooks replaced most render props, but they're still the standard for headless components and virtualization. - Compound components. A group of components that work together and share state through a private context:
import { createContext, useContext, useState, type ReactNode } from 'react';
const TabsContext = createContext<{ active: string; setActive: (id: string) => void } | null>(null);
const useTabs = () => {
const ctx = useContext(TabsContext);
if (!ctx) throw new Error('Tabs.* must be used inside <Tabs>');
return ctx;
};
export function Tabs({ defaultTab, children }: { defaultTab: string; children: ReactNode }) {
const [active, setActive] = useState(defaultTab);
return <TabsContext value={{ active, setActive }}>{children}</TabsContext>;
}
Tabs.Tab = function Tab({ id, children }: { id: string; children: ReactNode }) {
const { active, setActive } = useTabs();
return <button role="tab" aria-selected={active === id} onClick={() => setActive(id)}>{children}</button>;
};
Tabs.Panel = function Panel({ id, children }: { id: string; children: ReactNode }) {
return useTabs().active === id ? <div role="tabpanel">{children}</div> : null;
};
// <Tabs defaultTab="profile">
// <Tabs.Tab id="profile">Profile</Tabs.Tab> <Tabs.Tab id="billing">Billing</Tabs.Tab>
// <Tabs.Panel id="profile">...</Tabs.Panel> <Tabs.Panel id="billing">...</Tabs.Panel>
// </Tabs>
The caller arranges the pieces freely (tabs in a toolbar, panels elsewhere), and the state stays in one place. Radix, React Aria and
most design systems are built this way. (The value object here isn't memoized because it barely matters: Tabs re-renders when
active changes, which every tab needs to see anyway, or when its parent re-renders, which re-renders the tabs and panels the
parent created anyway.)
External stores and useSyncExternalStore
State that lives outside React (a store module, the browser's online status, localStorage, a WebSocket feed) needs a safe way to
feed components. That's useSyncExternalStore(subscribe, getSnapshot). The store side is small:
function createStore<T>(initial: T) {
let state = initial;
const listeners = new Set<() => void>();
return {
getSnapshot: () => state,
subscribe(listener: () => void) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
setState(next: T) {
if (Object.is(next, state)) return;
state = next; // a new immutable snapshot...
listeners.forEach((l) => l()); // ...then tell React to read it
},
};
}
const cart = createStore({ items: [] as string[] });
const stop = cart.subscribe(() => console.log('changed:', cart.getSnapshot().items.join(', ')));
cart.setState({ items: [...cart.getSnapshot().items, 'T-shirt'] });
cart.setState(cart.getSnapshot()); // same snapshot: no notification
stop();
import { useSyncExternalStore } from 'react';
export function useCartItems() {
return useSyncExternalStore(cart.subscribe, () => cart.getSnapshot().items);
}
function subscribeOnline(callback: () => void) { // defined outside the component: a stable function
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
export const useOnlineStatus = () => useSyncExternalStore(subscribeOnline, () => navigator.onLine, () => true);
The contract, and the bugs you get when you break it:
getSnapshotmust return the same value while nothing has changed. React calls it on every render and compares withObject.is. Returning a new object each time (() => ({ ...store.state }), or a selector like(s) => s.items.filter(...)) makes React think the store changed on every check: it logs "The result of getSnapshot should be cached to avoid an infinite loop" and keeps re-rendering until it gives up with "Maximum update depth exceeded". Return stored values, primitives, or results memoized on the snapshot.
const store = { state: { todos: ['write tests'], filter: 'all' } };
const copyEachTime = () => ({ ...store.state });
const sameObject = () => store.state;
console.log('copy is stable?', Object.is(copyEachTime(), copyEachTime())); // React would loop
console.log('state is stable?', Object.is(sameObject(), sameObject()));
subscribeshould be stable. If it's a new function on every render, React unsubscribes and resubscribes every time. Define it outside the component or memoize it.- Why not
useState+useEffect? With concurrent rendering, React can pause halfway through rendering a tree. If the store changes during that pause, components rendered before and after it would show different values (tearing).useSyncExternalStoredetects that and re-renders synchronously, and it reads the first value during render, so there's no flash of the initial state. - The third argument,
getServerSnapshot, is the value used during server rendering and hydration.
Exercises 4, 5 and 6 build each side of this contract: the component side, a Zustand-style store with selectors, and a
localStorage-backed store.
When to reach for Zustand or Redux Toolkit
Both are external stores with selector hooks, so components re-render only when the slice they select changes.
import { create } from 'zustand';
import { useShallow } from 'zustand/react/shallow';
type CartState = { items: CartItem[]; add: (item: CartItem) => void; clear: () => void };
export const useCart = create<CartState>()((set) => ({
items: [],
add: (item) => set((s) => ({ items: [...s.items, item] })), // set merges the top level
clear: () => set({ items: [] }),
}));
function CartBadge() {
const count = useCart((s) => s.items.length); // re-renders only when the count changes
return <span className="badge">{count}</span>;
}
function CartActions() {
const { add, clear } = useCart(useShallow((s) => ({ add: s.add, clear: s.clear }))); // pick several: shallow compare
return <button onClick={clear}>Clear</button>;
}
import { configureStore, createSlice, type PayloadAction } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState: { items: [] as CartItem[] },
reducers: {
added(state, action: PayloadAction<CartItem>) {
state.items.push(action.payload); // Immer turns this "mutation" into an immutable update
},
cleared(state) {
state.items = [];
},
},
});
export const store = configureStore({ reducer: { cart: cartSlice.reducer } });
export type RootState = ReturnType<typeof store.getState>;
// In components: const count = useSelector((s: RootState) => s.cart.items.length); dispatch(cartSlice.actions.added(item));
| The state is... | Use |
|---|---|
| used by one component | useState / useReducer |
| shared by a few nearby components | lift it up |
| read in many places, changes rarely (theme, user, locale, flags) | context |
| client state read in many places that changes often, or needs selectors | Zustand (small API, little boilerplate) |
| complex client state with many actions, middleware, time-travel debugging and strict team conventions | Redux Toolkit |
| data from the server | TanStack Query or RTK Query, not a hand-written store |
| filters, page, selected tab | the URL (router search params) |
Common gotchas: in Zustand v5, a selector that returns a new object or array on every call causes the same infinite-loop error
as an uncached getSnapshot; wrap it in useShallow. In Redux, useSelector((s) => s.cart.items.filter(...)) returns a new array
every time and re-renders on every store change; memoize with createSelector.
Common mistakes
- An inline object or function as a provider
value, re-rendering every consumer on each render of the provider. - One giant
AppContextholding everything, so every change re-renders every consumer. - Using context for fast-changing values (mouse position, a timer, every keystroke of a large form).
- Custom hooks that return a new object every render, then get used as effect dependencies.
getSnapshotor a store selector that builds a new object or array on every call.- A
subscribefunction created inside the component. - Copying server data into Redux or Zustand by hand instead of using a query library.
In a real codebase
Side note
- The app root stacks providers:
QueryClientProvider, the router, a theme provider, i18n, and authentication: the identity provider's OIDC client wrapped in a provider, with hooks for the signed-in user. For exampleAuthenticator.ProvideranduseAuthenticator()from Amplify UI for Amazon Cognito,MsalProvideranduseMsal()for Microsoft Entra ID, a small context around Firebase Auth'sonAuthStateChangedfor Google Cloud Identity Platform, orAuthProvideranduseAuth()fromreact-oidc-contextfor Auth0, Okta or Keycloak. - Features expose a provider plus a hook (
<OrderDraftProvider>anduseOrderDraft()), and keep the context object private. - A store module (Zustand or Redux Toolkit) for cross-cutting client state, with small selector hooks (
useCartCount()) so components never touch the whole state. - If you know Angular: context plays the role of DI providers in the component tree (
providers: [...]on a component), a custom hook is like a small injectable service that's instantiated per component, and a Zustand or NgRx-style store with selectors is the same idea in both frameworks.
The exercises
- Context provider stack: the nearest provider wins, defaults, nesting, and restoring values even when rendering throws.
- usePagination logic: the pure function behind a pagination hook, with clamping instead of an effect.
- Who re-renders?: state changes,
memoboundaries, and context consumers that bypass them. - The useSyncExternalStore contract: the component side: cached snapshots, stable subscriptions, and changes during subscribe.
- Mini Zustand: a typed store with
set/get, shallow merges, selector subscriptions andshallowequality. - localStorage store: a
useSyncExternalStore-ready store with cached parsing, validation and cross-tab updates.
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app