React hooks, effects, custom hooks and context
Hooks are the functions that give React components memory, side effects and access to shared values. This page starts with the rules every hook follows and the built-in hooks you will use most, then covers effects (the most misused hook), custom hooks that package logic for reuse, and context for values that many components need. The examples come from OrdersPortal’s order detail screen: a live status feed, an order loader and a session with the current user and display currency.
The samples target React 19.3. Each one was bundled with esbuild, rendered into a jsdom document with react-dom/client in Node.js 22, and driven with act() by the short driver at the end of the sample; the printed output is shown below each.
Topics on this page
Section titled “Topics on this page”| Topic | Use it to |
|---|---|
| Rules of hooks | Know which hooks exist and the two rules that keep them working. |
| Effects | Synchronize a component with something outside React, and know when not to. |
| Custom hooks | Reuse stateful logic such as data loading across components. |
| Context | Share values such as the signed-in user without passing props through every level. |
Rules of hooks
Section titled “Rules of hooks”A hook is a function whose name starts with use. React identifies each hook call by its order within the component, so two rules apply: call hooks only at the top level of a component or custom hook (never inside conditions, loops, nested functions or after an early return), and call them only from React function components or other custom hooks. The eslint-plugin-react-hooks lint rules enforce both, and also check effect dependency arrays; keep them on.
The built-in hooks fall into a few groups:
| Need | Hooks |
|---|---|
| Remember values between renders | useState, useReducer for named state transitions |
| Hold a mutable value or DOM node that does not trigger a render | useRef |
| Synchronize with external systems | useEffect, useLayoutEffect (before paint), useEffectEvent (React 19.2) |
| Read shared values | useContext, and use(Context) which may be called conditionally |
| Avoid repeated work | useMemo, useCallback (often unnecessary with the React Compiler) |
| Keep the UI responsive | useTransition, useDeferredValue |
| Forms and server mutations | useActionState, useOptimistic, useFormStatus (React 19) |
| Subscribe to an external store | useSyncExternalStore |
| Read promises during render | use(promise) with a Suspense boundary (React 19) |
use is the one exception to the ordering rule: it can be called inside conditions and loops, though still not in try/catch.
Pitfalls:
- Conditional hooks.
if (isAdmin) useState(...)shifts every later hook by one slot when the condition changes, and React throws. - Hooks in plain helpers. A function that calls hooks must itself be a component or a hook named
use..., otherwise the lint rules cannot check it and callers may break the rules. - Disabling the dependency lint rule usually hides a stale-value bug rather than fixing it.
Effects
Section titled “Effects”useEffect(setup, dependencies) runs code after React has updated the screen, to keep a component synchronized with a system outside React: a WebSocket, a browser API, a third-party widget, a timer. The setup function can return a cleanup function. React runs setup after the first render, runs cleanup and then setup again whenever a value in the dependency array changes, and runs cleanup when the component unmounts. Every reactive value the effect reads (props, state, values derived from them) belongs in the array.
In development with StrictMode, React runs one extra setup and cleanup cycle on mount as a stress test; if that causes visible problems, the cleanup does not fully undo the setup.
Many effects are unnecessary. If you can calculate something from props and state, calculate it during render. If something should happen because the user clicked, do it in the event handler. To reset all state when an ID changes, render the component with key={orderId}. When an effect needs the latest value of something without re-running when it changes (for example the current theme inside a “connected” notification), wrap that logic in useEffectEvent, available since React 19.2.
import { useEffect, useState } from 'react';
// An external system: a tiny pub/sub standing in for a WebSocket feed.const statusFeed = { listeners: new Map(), subscribe(orderId, callback) { console.log(`subscribe ${orderId}`); this.listeners.set(orderId, callback); return () => { console.log(`unsubscribe ${orderId}`); this.listeners.delete(orderId); }; }, publish(orderId, status) { this.listeners.get(orderId)?.(status); },};
function LiveStatus({ orderId }) { const [latest, setLatest] = useState(null);
useEffect(() => { const unsubscribe = statusFeed.subscribe(orderId, (status) => setLatest({ orderId, status })); return unsubscribe; // cleanup runs before the next effect and on unmount }, [orderId]); // re-subscribe only when orderId changes
// Derive instead of resetting state in the effect. const status = latest?.orderId === orderId ? latest.status : 'unknown';
return <p>Order {orderId}: {status}</p>;}
// Driverimport { act } from 'react';import { createRoot } from 'react-dom/client';const root = createRoot(document.getElementById('root'));const text = () => console.log(document.querySelector('p').textContent);await act(() => root.render(<LiveStatus orderId={1001} />));await act(() => statusFeed.publish(1001, 'packed')); text();await act(() => root.render(<LiveStatus orderId={1002} />));await act(() => statusFeed.publish(1001, 'shipped')); text(); // old order: ignoredawait act(() => statusFeed.publish(1002, 'paid')); text();await act(() => root.unmount());Output:
subscribe 1001Order 1001: packedunsubscribe 1001subscribe 1002Order 1002: unknownOrder 1002: paidunsubscribe 1002When orderId changes, React unsubscribes from 1001 before subscribing to 1002, so a late message for order 1001 is ignored. The displayed status is derived from the last event and the current ID rather than reset inside the effect.
Pitfalls:
- Missing cleanup. Subscriptions, intervals and listeners without cleanup leak and fire for stale data.
- Effects that only transform data (
useEffect(() => setTotal(...), [lines])) cause an extra render with stale output first; compute the value during render. - Objects and functions created during render in the dependency array change every render and re-run the effect every time; move them inside the effect or depend on primitive values.
Custom hooks
Section titled “Custom hooks”A custom hook is a function named use... that calls other hooks. It lets several components share stateful logic (each call gets its own independent state) while keeping the component focused on rendering. Good custom hooks are named after their purpose rather than their mechanics (useOrder, useOnlineStatus, not useFetchEffect), take the minimum inputs, and return a small, stable shape.
Data loading is the classic example and a good illustration of what effects need to get right: abort or ignore responses for an old ID when the ID changes, distinguish loading, error and ready states, and never show the previous order while the next one loads. For production apps, a data-fetching library (TanStack Query, SWR) or your framework’s loaders add caching, deduplication and retries on top of the same idea; the hook below shows the underlying pattern and keeps fetch injectable for tests.
import { useEffect, useState } from 'react';
// Custom hook: load one order, cancel stale requests, expose a small state machine.export function useOrder(orderId, fetchImpl = fetch) { const [state, setState] = useState({ status: 'loading', order: null, error: null, orderId });
useEffect(() => { const controller = new AbortController(); fetchImpl(`https://api.example.test/orders/${orderId}`, { signal: controller.signal }) .then((res) => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); }) .then((order) => setState({ status: 'ready', order, error: null, orderId })) .catch((error) => { if (error.name !== 'AbortError') setState({ status: 'error', order: null, error, orderId }); }); return () => controller.abort(); // a newer orderId cancels the older request }, [orderId, fetchImpl]);
// While a new id is loading, do not show the previous order. return state.orderId === orderId ? state : { status: 'loading', order: null, error: null, orderId };}
function OrderHeader({ orderId, fetchImpl }) { const { status, order, error } = useOrder(orderId, fetchImpl); if (status === 'loading') return <p>Loading order {orderId}...</p>; if (status === 'error') return <p role="alert">Could not load order {orderId}: {error.message}</p>; return <h2>Order {order.id} for {order.customer}</h2>;}
// Driver: a fake fetch where order 1001 is slow and 404 for unknown ids.import { act } from 'react';import { createRoot } from 'react-dom/client';const db = { 1001: { id: 1001, customer: 'Ada Lopez' }, 1002: { id: 1002, customer: 'Ben Ortiz' } };const fakeFetch = (url, { signal }) => new Promise((resolve, reject) => { const id = Number(url.split('/').pop()); let answered = false; const timer = setTimeout(() => { answered = true; resolve({ ok: id in db, status: id in db ? 200 : 404, json: async () => db[id] }); }, id === 1001 ? 50 : 5); signal.addEventListener('abort', () => { if (answered) return; clearTimeout(timer); console.log(`aborted request for ${id}`); reject(new DOMException('Aborted', 'AbortError')); });});const root = createRoot(document.getElementById('root'));const show = () => console.log(document.getElementById('root').textContent);const wait = (ms) => act(() => new Promise((r) => setTimeout(r, ms)));await act(() => root.render(<OrderHeader orderId={1001} fetchImpl={fakeFetch} />)); show();await act(() => root.render(<OrderHeader orderId={1002} fetchImpl={fakeFetch} />)); // switch before 1001 answersawait wait(80); show();await act(() => root.render(<OrderHeader orderId={9999} fetchImpl={fakeFetch} />));await wait(20); show();Output:
Loading order 1001...aborted request for 1001Order 1002 for Ben OrtizCould not load order 9999: HTTP 404Other common custom hooks follow the same pattern: useDebouncedValue(value, delay) with a timer and cleanup, useMediaQuery(query) and useLocalStorage(key) built on useSyncExternalStore so every component reading the same store stays consistent, and useClickOutside(ref, onOutside) with a document listener and cleanup.
Pitfalls:
- Race conditions. Without aborting or ignoring old requests, a slow response for order 1001 can overwrite the faster one for 1002.
- Expecting shared state. Two components calling
useOrder(1001)make two requests and hold two copies; share with context or a cache library. - Returning new objects or functions every render can trigger effects in callers; return stable values or let the React Compiler memoize them.
Context
Section titled “Context”Context passes a value to every component below a provider without threading props through each level. Create it with createContext(defaultValue), provide it by rendering <SessionContext value={...}> (React 19; <SessionContext.Provider> is the older form, still supported), and read it with useContext(SessionContext) or use(SessionContext). The nearest provider above the reading component wins, so you can override a value for a subtree.
Context fits values that many components at different depths read and that change rarely: the signed-in user, locale and display currency, theme, feature flags. Every consumer re-renders when the provided value changes, so memoize object values, split rarely-changing values (user) from frequently-changing ones, and keep fast-changing state such as form input or a live cursor out of broad contexts. Wrapping the context in a custom hook gives a clear error when a provider is missing and hides the context object from consumers.
import { createContext, useContext, useMemo, useState } from 'react';
const SessionContext = createContext(null);
export function SessionProvider({ user, children }) { const [currency, setCurrency] = useState('EUR'); // Memoize so consumers re-render only when user or currency actually change. const value = useMemo(() => ({ user, currency, setCurrency }), [user, currency]); return <SessionContext value={value}>{children}</SessionContext>; // React 19: no .Provider}
export function useSession() { const session = useContext(SessionContext); if (session === null) throw new Error('useSession must be used inside SessionProvider'); return session;}
function CurrencySwitch() { const { currency, setCurrency } = useSession(); return <button onClick={() => setCurrency(currency === 'EUR' ? 'USD' : 'EUR')}>Show in {currency === 'EUR' ? 'USD' : 'EUR'}</button>;}
function OrderTotal({ amountEur }) { const { currency, user } = useSession(); const amount = currency === 'EUR' ? amountEur : amountEur * 1.08; // fixed demo rate return <p>{user.name} sees {amount.toFixed(2)} {currency}</p>;}
// Driverimport { act } from 'react';import { createRoot } from 'react-dom/client';const root = createRoot(document.getElementById('root'));await act(() => root.render( <SessionProvider user={{ name: 'Ada' }}> <OrderTotal amountEur={61.98} /> <CurrencySwitch /> </SessionProvider>));console.log(document.querySelector('p').textContent);await act(() => document.querySelector('button').click());console.log(document.querySelector('p').textContent);try { await act(() => root.render(<OrderTotal amountEur={1} />));} catch (error) { console.log(error.message);}Output:
Ada sees 61.98 EURAda sees 66.94 USDuseSession must be used inside SessionProviderPitfalls:
- Context as a global store. Putting all app state in one context re-renders every consumer on every change; use several small contexts, or a store library (Zustand, Redux Toolkit) for frequently updated shared state and a query library for server data.
- A new object every render (
value={{ user, currency }}) re-renders all consumers even when nothing changed, unless the React Compiler memoizes it. - Default values that hide bugs. A meaningful default lets a missing provider go unnoticed; default to
nulland throw in the hook.
Choosing between them
Section titled “Choosing between them”| Situation | Use |
|---|---|
| Value computed from props or state | Plain calculation during render |
| Reaction to a user action | Event handler |
| Connection to a socket, timer, browser API or widget | useEffect with cleanup |
| Same stateful logic in several components | Custom hook |
| Value read by many components at different depths, changes rarely | Context |
| Server data with caching and refetching | Data-fetching library or framework loaders |
Interview questions
Section titled “Interview questions”Why must hooks be called in the same order on every render? React stores hook state in a list per component and matches each call to its slot by position. A conditional hook shifts the positions, so state would attach to the wrong hook; React detects this and throws.
What does the dependency array do, and what happens with an empty array?
It lists the reactive values the effect reads; React re-runs cleanup and setup when any of them changes, compared with Object.is. An empty array means “run after mount and clean up on unmount”, which is correct only if the effect truly reads no props or state.
When would you not use an effect?
For data transformations (compute during render), for responses to user actions (event handlers), for resetting state on prop change (use a key), and for sharing data between components (lift state or use context). Effects are for synchronizing with external systems.
How do you avoid race conditions when fetching in an effect?
Abort the previous request with an AbortController in the cleanup, or set an ignore flag in the cleanup and check it before setting state. Libraries such as TanStack Query handle this and caching for you.
Senior scenario: the order screen re-renders 40 components whenever the session’s clock ticks every second. The clock lives in the same context as the user. How do you fix it?
Split the context: the user and currency go in a stable, memoized context; the clock moves to its own context read only by the components that display time, or to a small store read with useSyncExternalStore. Verify with the React DevTools Profiler, and consider enabling the React Compiler so incidental object identities stop causing re-renders.
Related pages
Section titled “Related pages”- Components, props and state for the basics these hooks build on.
- Forms and routing for
useActionState,useOptimisticand router data loading. - Performance for memoization, transitions and the React Compiler.
- React interview questions