You know useState. You've fought with useEffect. But React ships 19 hooks as of React 19, and most developers have only internalized four or five of them. The rest sit in the docs like strangers at a party — technically present, rarely talked to.
This is the reference you bookmark. Every hook, every pattern, every mistake that will cost you an afternoon if you don't know about it.
Quick Reference Table
| Hook | Category | What It Does |
|---|---|---|
useState | State | Local component state |
useReducer | State | Complex state with actions |
useEffect | Side effects | Run code after render |
useLayoutEffect | Side effects | Run code before paint |
useInsertionEffect | Side effects | Inject styles before DOM mutations |
useContext | Context | Consume a React context |
useRef | Refs | Mutable ref, DOM access |
useImperativeHandle | Refs | Customize exposed ref handle |
useMemo | Performance | Memoize expensive computations |
useCallback | Performance | Memoize function references |
useId | Utility | Generate unique IDs |
useDebugValue | Utility | Label custom hooks in DevTools |
useDeferredValue | Concurrency | Defer a non-urgent value |
useTransition | Concurrency | Mark state updates as non-urgent |
useSyncExternalStore | External stores | Subscribe to external data |
useActionState | Forms (React 19) | Manage form action state |
useFormStatus | Forms (React 19) | Read parent form submission status |
useOptimistic | Forms (React 19) | Optimistic UI updates |
use | Resource reading (React 19) | Read promises and contexts inline |
1. useState
The foundation of interactive React. useState gives a component its own memory — a value that persists between renders and triggers a re-render when it changes.
Syntax
const [state, setState] = useState(initialValue);
initialValue can be a primitive, object, array, or a function (lazy initialization). The setter setState accepts a new value or an updater function that receives the previous state.
Practical Example
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
Common Mistakes
Mutating state directly. React won't detect the change and won't re-render.
// Wrong
state.items.push(newItem);
setState(state);
// Correct
setState(prev => ({ ...prev, items: [...prev.items, newItem] }));
Stale closures in event handlers. If your update depends on the current value, always use the updater function form — not the snapshot from the closure.
// Can produce stale values
setCount(count + 1);
// Always safe
setCount(prev => prev + 1);
Expensive initial state running every render. Pass a function, not a function call.
// Runs on every render (wasteful)
const [data, setData] = useState(parseHeavyData(rawData));
// Runs once (correct lazy init)
const [data, setData] = useState(() => parseHeavyData(rawData));
2. useReducer
When state logic gets complex — multiple sub-values, next state depending on previous state, or actions that affect multiple fields — useReducer is cleaner than a stack of useState calls.
Syntax
const [state, dispatch] = useReducer(reducer, initialState, init?);
The optional init function is used for lazy initialization, same as useState.
Practical Example
const initialState = { count: 0, step: 1 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { ...state, count: state.count + state.step };
case 'decrement': return { ...state, count: state.count - state.step };
case 'setStep': return { ...state, step: action.payload };
case 'reset': return initialState;
default: throw new Error(`Unknown action: ${action.type}`);
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>Count: {state.count} (step: {state.step})</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<input
type="number"
value={state.step}
onChange={e => dispatch({ type: 'setStep', payload: Number(e.target.value) })}
/>
</div>
);
}
Common Mistakes
Returning undefined from the reducer. Every case (including default) must return a state object. A missing return silently sets state to undefined and breaks everything downstream.
Passing the reducer inline. Define it outside the component so it isn't recreated on every render.
Date.now() inside them. If you need side effects after a dispatch, put them in useEffect watching the state that changed.
3. useEffect
useEffect runs after the browser paints. It's the hook for synchronizing your component with the outside world: fetching data, subscribing to events, setting timers, or integrating with third-party libraries.
Syntax
useEffect(() => {
// setup code
return () => {
// cleanup code (optional)
};
}, [dependencies]);
- No dependency array: runs after every render.
- Empty array
[]: runs once after the first render. - Array with values
[a, b]: runs after renders whereaorbchanged.
Practical Example
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let cancelled = false;
async function fetchUser() {
const data = await getUser(userId);
if (!cancelled) setUser(data);
}
fetchUser();
return () => { cancelled = true; };
}, [userId]);
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
Common Mistakes
Missing the cleanup function. Without it, subscriptions and async operations from old renders keep running and can set state on unmounted components.
Omitting dependencies. The linter rule exhaustive-deps exists for a reason. If you reference a value from the component scope inside the effect but exclude it from the array, you get stale data on future renders.
Overusing useEffect for derived data. If something can be calculated directly from props or state during render, calculate it during render. Reserve useEffect for true synchronization with external systems.
useEffect as "when this dependency changes, do this synchronization." If you can't articulate what external system you're synchronizing with, you probably don't need an effect.
4. useLayoutEffect
Identical API to useEffect, but fires synchronously after all DOM mutations and before the browser paints. Use this when you need to read layout and synchronously re-render to prevent a visual flicker.
Syntax
useLayoutEffect(() => {
// runs before browser paint
return () => { /* cleanup */ };
}, [dependencies]);
Practical Example
function Tooltip({ targetRef, children }) {
const tooltipRef = useRef(null);
useLayoutEffect(() => {
const target = targetRef.current.getBoundingClientRect();
const tooltip = tooltipRef.current;
tooltip.style.top = `${target.bottom + 8}px`;
tooltip.style.left = `${target.left}px`;
}, [targetRef]);
return <div ref={tooltipRef} className="tooltip">{children}</div>;
}
Common Mistakes
Using it where useEffect is fine. useLayoutEffect blocks painting and can hurt performance. Default to useEffect; switch to useLayoutEffect only when you see a flicker.
Server-side rendering. useLayoutEffect does not run on the server. If you use it in a component that renders server-side, React will warn you. Use useEffect or gate execution with typeof window !== 'undefined'.
5. useContext
Reads the current value of a React context without prop drilling. Any component that calls useContext subscribes to context changes and re-renders when the value updates.
Syntax
const value = useContext(SomeContext);
Practical Example
const ThemeContext = React.createContext('light');
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
className={`btn-${theme}`}
onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}
>
Current theme: {theme}
</button>
);
}
Common Mistakes
Putting too much in a single context. Every consumer re-renders when the value changes. Split unrelated data into separate contexts — one for auth, one for theme, one for UI state — so components only re-render for changes they care about.
Passing a new object as the value on every render. <Context.Provider value={{ user, logout }}> creates a new object every render, causing all consumers to re-render even when nothing changed. Memoize it with useMemo.
useSyncExternalStore.
6. useRef
useRef returns a mutable container whose .current property persists for the lifetime of the component without triggering re-renders when it changes. Two primary uses: accessing DOM nodes and holding mutable values that don't drive the UI.
Syntax
const ref = useRef(initialValue);
Practical Example
function VideoPlayer({ isPlaying }) {
const videoRef = useRef(null);
useEffect(() => {
if (!videoRef.current) return;
isPlaying ? videoRef.current.play() : videoRef.current.pause();
}, [isPlaying]);
return <video ref={videoRef} src="/video.mp4" />;
}
// Storing a mutable value (previous render's prop)
function usePrevious(value) {
const ref = useRef();
useEffect(() => { ref.current = value; });
return ref.current;
}
Common Mistakes
Treating ref changes as reactive. Changing ref.current does not trigger a re-render. If the UI needs to react to the change, use useState instead.
Reading a ref during render. Refs are meant to be read and written in event handlers or effects, not during rendering (with the exception of lazy initialization patterns).
7. useImperativeHandle
Lets you customize what a parent component sees when it holds a ref to a child component. Use it to expose only a controlled API instead of the raw DOM node.
Syntax
useImperativeHandle(ref, () => ({
// methods and properties to expose
}), [dependencies]);
Practical Example
const FancyInput = React.forwardRef(function FancyInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() { inputRef.current.focus(); },
clear() { inputRef.current.value = ''; },
}));
return <input ref={inputRef} {...props} />;
});
// Parent
function Form() {
const inputRef = useRef(null);
return (
<>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
<button onClick={() => inputRef.current.clear()}>Clear</button>
</>
);
}
Common Mistakes
Overexposing the DOM node. If you forward the raw ref, the parent can reach into any DOM property. useImperativeHandle gives you a deliberate, versioned surface area for the parent API.
useImperativeHandle frequently, consider whether the parent should be driving state instead. Imperative APIs in React are usually a last resort.
8. useMemo
Memoizes the result of an expensive computation so it only recalculates when its dependencies change.
Syntax
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Practical Example
function ProductList({ products, filterText }) {
const filtered = useMemo(
() => products.filter(p => p.name.toLowerCase().includes(filterText.toLowerCase())),
[products, filterText]
);
return <ul>{filtered.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}
Common Mistakes
Memoizing cheap operations. The overhead of useMemo itself (allocating closures, checking dependencies) can exceed the cost of just running a fast calculation every render. Profile before optimizing.
Using it for object identity to prevent child re-renders. This works, but useCallback is the idiomatic choice for functions, and useMemo for objects/arrays.
useMemo speculatively. Add it reactively, when profiling shows a specific expensive calculation is a bottleneck.
9. useCallback
Memoizes a function reference so it doesn't change on every render. Primarily useful when passing callbacks to child components wrapped in React.memo, or as a dependency of another hook.
Syntax
const memoizedFn = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Practical Example
const Row = React.memo(function Row({ item, onDelete }) {
return <li>{item.name} <button onClick={() => onDelete(item.id)}>Delete</button></li>;
});
function List({ items }) {
const [list, setList] = useState(items);
const handleDelete = useCallback((id) => {
setList(prev => prev.filter(item => item.id !== id));
}, []); // stable: only uses the setter, which React guarantees is stable
return <ul>{list.map(item => <Row key={item.id} item={item} onDelete={handleDelete} />)}</ul>;
}
Common Mistakes
Using useCallback on every function in your component. It only helps if the function is a dependency of another hook or a prop to a memoized child. In all other cases it adds overhead for no benefit.
Forgetting dependencies. A useCallback with missing deps returns a stale closure — the most confusing class of React bug there is.
10. useId
Generates a stable, unique ID that is consistent between server and client renders. Designed specifically to solve the SSR hydration mismatch problem when linking form labels to inputs.
Syntax
const id = useId();
Practical Example
function FormField({ label }) {
const id = useId();
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} type="text" />
</div>
);
}
Common Mistakes
Using it for list keys. useId generates the same ID across renders for a given component instance — it does not produce a unique key per list item. Use your data's own IDs for list keys.
11. useDebugValue
Adds a custom label to custom hooks in React DevTools. It has no effect in production and no impact on behavior.
Syntax
useDebugValue(value, formatFn?);
Practical Example
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useDebugValue(isOnline ? 'Online' : 'Offline');
useEffect(() => {
const handler = () => setIsOnline(navigator.onLine);
window.addEventListener('online', handler);
window.addEventListener('offline', handler);
return () => {
window.removeEventListener('online', handler);
window.removeEventListener('offline', handler);
};
}, []);
return isOnline;
}
The optional second argument is a formatting function — use it to defer expensive formatting so it only runs when DevTools is open.
12. useDeferredValue
Accepts a value and returns a deferred version of it. During urgent updates (typing, clicking), React keeps showing the old deferred value while rendering the new one in the background. Analogous to debouncing but driven by React's scheduler.
Syntax
const deferredValue = useDeferredValue(value);
Practical Example
function SearchResults({ query }) {
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<div style={{ opacity: isStale ? 0.7 : 1 }}>
<SlowList query={deferredQuery} />
</div>
);
}
The input stays responsive immediately; the slow list re-renders when the scheduler has capacity.
13. useTransition
Marks a state update as non-urgent, allowing React to interrupt it for higher-priority work. Returns a isPending boolean you can use to show a loading indicator.
Syntax
const [isPending, startTransition] = useTransition();
Practical Example
function TabContainer() {
const [tab, setTab] = useState('home');
const [isPending, startTransition] = useTransition();
function selectTab(next) {
startTransition(() => setTab(next));
}
return (
<>
<TabBar onSelect={selectTab} />
{isPending && <Spinner />}
<TabContent tab={tab} />
</>
);
}
Common Mistakes
Wrapping urgent updates in startTransition. Typing in an input must stay urgent. Only wrap things the user can wait a beat for: navigating to a new tab, filtering a large list, loading heavy content.
useDeferredValue and useTransition solve the same problem from different angles. If you control the state setter, use useTransition. If you receive a value as a prop and can't control how it's set, use useDeferredValue.
14. useSyncExternalStore
The correct way to subscribe to external data stores (Redux, Zustand, browser APIs) in a way that's compatible with React's concurrent rendering. Before this hook, direct subscriptions could cause tearing.
Syntax
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?);
subscribe: a function that registers a callback and returns an unsubscribe function.getSnapshot: returns the current value from the store.getServerSnapshot: returns the value for SSR.
Practical Example
function useWindowWidth() {
return useSyncExternalStore(
(callback) => {
window.addEventListener('resize', callback);
return () => window.removeEventListener('resize', callback);
},
() => window.innerWidth,
() => 1024 // server fallback
);
}
15. useInsertionEffect
A specialized hook for CSS-in-JS library authors. Fires before any DOM mutations, giving libraries a slot to inject <style> tags before layout effects read the DOM. If you're not writing a CSS-in-JS library, you will almost certainly never need this.
Syntax
useInsertionEffect(() => {
// inject styles
return () => { /* cleanup */ };
}, [dependencies]);
16. useActionState (React 19)
Manages state derived from a form action. Takes an async action function and an initial state, returns the current state and a form action you attach directly to a <form>.
Syntax
const [state, formAction, isPending] = useActionState(action, initialState);
Practical Example
async function submitContact(prevState, formData) {
const email = formData.get('email');
const result = await sendEmail(email);
return result.ok ? { success: true } : { error: 'Failed to send.' };
}
function ContactForm() {
const [state, formAction, isPending] = useActionState(submitContact, null);
return (
<form action={formAction}>
<input name="email" type="email" required />
<button type="submit" disabled={isPending}>
{isPending ? 'Sending...' : 'Send'}
</button>
{state?.error && <p className="error">{state.error}</p>}
{state?.success && <p>Email sent!</p>}
</form>
);
}
17. useFormStatus (React 19)
Reads the pending status of the nearest parent <form> submission. Must be used inside a component that is a child of a <form> — it cannot be in the same component as the form itself.
Syntax
const { pending, data, method, action } = useFormStatus();
Practical Example
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Submitting...' : 'Submit'}
</button>
);
}
function MyForm() {
return (
<form action={someAction}>
<input name="name" />
<SubmitButton /> {/* SubmitButton reads the form's pending state */}
</form>
);
}
18. useOptimistic (React 19)
Applies an optimistic update to the UI immediately while an async operation runs in the background. If the operation fails, React automatically reverts to the original state.
Syntax
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn);
Practical Example
function MessageList({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, newMessage) => [...current, { ...newMessage, pending: true }]
);
async function handleSend(formData) {
const text = formData.get('text');
addOptimisticMessage({ id: Date.now(), text });
await sendMessage(text);
}
return (
<>
<ul>
{optimisticMessages.map(m => (
<li key={m.id} style={{ opacity: m.pending ? 0.6 : 1 }}>{m.text}</li>
))}
</ul>
<form action={handleSend}>
<input name="text" /><button type="submit">Send</button>
</form>
</>
);
}
19. use (React 19)
A versatile hook that can read resources — Promises and contexts — anywhere in a component, including conditionally. Unlike other hooks, use can be called inside loops and conditionals.
Syntax
const value = use(resource); // resource is a Promise or a Context
Practical Example
// Reading a promise (works with Suspense)
function UserCard({ userPromise }) {
const user = use(userPromise); // suspends until the promise resolves
return <h2>{user.name}</h2>;
}
// Conditionally reading context
function Notification({ type }) {
if (type === 'alert') {
const theme = use(ThemeContext); // legal — `use` can be called conditionally
return <div className={theme}>Alert!</div>;
}
return null;
}
Common Mistakes
Passing a new Promise on every render. Create promises outside the component or memoize them. A new use(newPromise) on every render creates an infinite suspend loop.
use with a Promise pairs with React's <Suspense> boundary. The component suspends while the promise is pending and renders when it resolves. Wrap it in a <Suspense fallback={<Spinner />}> in the parent.
Patterns Worth Knowing
Custom Hooks
Every hook in this guide composes. Custom hooks let you extract reusable logic into a named function that starts with use. They share logic, not state — each call to a custom hook gets its own isolated state.
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
} catch { return initialValue; }
});
const setAndPersist = useCallback((newValue) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
}, [key]);
return [value, setAndPersist];
}
The Rules of Hooks — and Why They Exist
React hooks have two rules:
- Only call hooks at the top level. Never inside loops, conditions, or nested functions.
- Only call hooks from React functions. Components or custom hooks.
These rules exist because React identifies hooks by call order. If a hook is conditionally skipped, the order shifts and React pairs state to the wrong hook. The use hook from React 19 is the only deliberate exception to rule one.
AI-Accelerated React Development
Hooks solve real problems, but writing boilerplate — the same custom useDebounce, useFetch, and useMediaQuery patterns for every project — is tedious. If you find yourself prompting an AI assistant for hook implementations repeatedly, a structured prompt library makes that workflow significantly faster.
AI Prompts for Developers from Imperial Products includes prompt templates for React hook generation, refactoring class components to hooks, performance audit prompts for identifying unnecessary re-renders, and more. Every prompt is structured to produce working, copy-paste-ready code rather than vague suggestions.
Which hook do you reach for most? Share your patterns in the comments.