Any React Hooks guide has to start with the same definition: hooks are functions that let a function component hold state, run side effects, read context and keep refs. They work only when you call them at the top level of the component, in the same order on every render. Nearly everything else about hooks follows from that rule.
You need fewer hooks than you might think. Most apps run on useState, useRef, useContext, custom hooks and a sparing amount of useEffect, which developers reach for far too often. React 19 added use, useActionState and useOptimistic for data, forms and optimistic UI. React 19.2 brought useEffectEvent to fix stale closures in effects.
As of November 2026, React Compiler has been stable for over a year, since October 2025. With it, hand-written useMemo and useCallback are becoming optional rather than routine.
Why hooks depend on call order
React doesn't know your hooks by name. It knows them by position. Every time a component renders, React walks a list of that component's hook calls in the order they run: slot one belongs to the first useState, slot two to whatever hook comes next, and so on. Each call gets back whatever is stored in its slot. That design shipped stable in React 16.8 in February 2019, and it's why function components could replace classes without any API for registering state.
It also explains every rule. Put a hook inside an if, and on renders where the condition is false, that slot gets skipped. Every hook after it shifts up one position, so your email state gets handed to the call that expected isOpen. So you call hooks only at the top level of a function component or a custom hook: never inside loops, conditions, nested functions or event handlers, and never in class components.
React 19's use() is the one exception. You can call it conditionally, though you still can't put it inside a try/catch.
You don't have to enforce any of this by memory. The rules-of-hooks lint rule in eslint-plugin-react-hooks catches violations, and the one it flags most often is a hook placed after an early return:
// Broken: when user is null, useState never runs, so slots shiftfunction Profile({ user }) { if (!user) return <Spinner />; const [tab, setTab] = useState('posts'); return <Tabs active={tab} onChange={setTab} />;}
// Fixed: the hook runs on every render, then you branchfunction Profile({ user }) { const [tab, setTab] = useState('posts'); if (!user) return <Spinner />; return <Tabs active={tab} onChange={setTab} />;}The fix is mechanical: move every hook above the first return, then branch on your data.
A React Hooks guide to choosing the right hook
Start from the problem in front of you, not the hook you half-remember, and the choice is rarely ambiguous:
| Need | Hook |
|---|---|
| Keep local state (a toggle, an input, a counter) | useState, or useReducer when several fields change together |
| Sync with an external system (subscription, timer, network connection) | useEffect |
| Measure the DOM before the browser paints | useLayoutEffect |
| Hold a mutable value or DOM node without triggering a re-render | useRef |
| Read context | useContext / use |
| Skip an expensive recalculation on every render | useMemo |
| Keep a function's identity stable between renders | useCallback |
| Mark an update as non-urgent so typing stays responsive | useTransition / useDeferredValue |
| Generate IDs that match on server and client, avoiding hydration mismatches | useId |
| Subscribe to an external store (browser APIs, Redux, Zustand) | useSyncExternalStore |
| Handle forms, mutations and pending states | useActionState / useFormStatus / useOptimistic |
| Read the latest props or state inside an effect without re-running it | useEffectEvent |
| Expose specific methods to a parent component | useImperativeHandle |
Managing component state
Most "state isn't updating" bugs come from one misunderstanding. Each render gets its own snapshot of state, and calling a setter doesn't change the variable you're holding. It asks React to render again with a new value.
Why state doesn't update right away
Inside one event handler, count is fixed for that render. Call setCount(count + 1) three times and you've asked for the same value three times, so the counter goes up by one. Pass an updater function instead, and React applies each one to the latest pending value:
function Counter() { const [count, setCount] = useState(0);
function addThree() { setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); }
return <button onClick={addThree}>{count}</button>;}Now each click adds 3.
React 18 made batching automatic everywhere, including inside timeouts, promises and native event listeners. React processes the updates together, so a console.log(count) on the line after a setter still prints the old value. You'll see the new one on the next render.
Two more details will save you debugging time.
- Lazy initial state: If the initial value is expensive to compute, pass the function itself.
useState(() => parseSavedDraft())runs the initializer once.useState(parseSavedDraft())runs it on every render and throws the result away. - Identical values skip the re-render: React compares the new value to the old one with
Object.is, and if they match, it doesn't re-render. That's whyuser.name = 'Ana'; setUser(user)does nothing: it's the same object. Create a new one withsetUser({ ...user, name: 'Ana' }).
When to reach for useReducer
useReducer earns its place when several fields change together, when the next state depends on the current one in nontrivial ways, or when you want to test the logic without rendering anything. A sign-up form is a typical case:
function formReducer(state, action) { switch (action.type) { case 'field': return { ...state, [action.name]: action.value, error: null }; case 'submit': return { ...state, status: 'submitting' }; case 'failed': return { ...state, status: 'idle', error: action.error }; default: return state; }}
const [form, dispatch] = useReducer(formReducer, { email: '', password: '', status: 'idle', error: null,});// <input onChange={e => dispatch({ type: 'field', name: 'email', value: e.target.value })} />The reducer is a plain function, so a few assertions can cover every transition, and the component only describes what happened. For a single toggle or input, stick with useState.
When to use useEffect
useEffect has one job: keeping a component in sync with something React doesn't control. That covers subscriptions, timers, manual DOM work and network connections such as a WebSocket. The effect sets the connection up, and the function it returns tears it down. React runs that cleanup before the effect runs again and when the component unmounts.
function Clock() { const [now, setNow] = useState(() => new Date());
useEffect(() => { const id = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(id); // stop the old timer }, []);
return <p>{now.toLocaleTimeString()}</p>;}Leave out that return and every remount leaves another interval ticking in the background.
You might not need an effect
If nothing outside React is involved, you probably don't need an effect. React's "You Might Not Need an Effect" page catalogs the misuses, and three of them cause most of the bugs.
The most common is copying derived data into state:
// Anti-pattern: redundant state, synced by an effectconst [visibleTodos, setVisibleTodos] = useState([]);useEffect(() => { setVisibleTodos(todos.filter(t => showDone || !t.done));}, [todos, showDone]);
// Fix: calculate it during renderconst visibleTodos = todos.filter(t => showDone || !t.done);The effect version renders once with a stale list and then again with the correct one, and it leaves you two sources of truth that can drift apart. Calculating during render gets rid of both. If the calculation is genuinely expensive, that's what useMemo is for.
To reset state when a prop changes, such as clearing a form when userId switches, render <Profile key={userId} />. React treats each user as a new component with fresh state, so you don't need an effect that wipes fields after the first render.
Logic caused by a specific user action, like sending an analytics event or POSTing a form on submit, belongs in the event handler. An effect watching a submitted flag runs at the wrong moment and fires again on remount.
Why your effect runs twice
In development, Strict Mode in React 18 and later mounts each component, unmounts it and mounts it again, so every effect runs setup, cleanup, setup. That's on purpose: an effect without proper cleanup shows up right away as two chat connections or a clock ticking at double speed. Production runs effects once. Don't respond by removing Strict Mode. That only hides a bug that'll come back when a user navigates away and returns. Write a cleanup that fully undoes the setup, and the double run stops mattering.
Getting dependency arrays right
The dependency array is a promise to React. It lists every prop, state value and function from the component that the effect reads, and React re-runs the effect whenever one of them changes. Leave one out and the effect keeps reading the props and state from the render where it last ran, indefinitely. That's a stale closure, and an eslint-disable comment on exhaustive-deps doesn't fix it. It just hides the warning.
When the linter complains, change the code instead of the array. If a function is only used by the effect, move it inside the effect. If the effect computes new state from old state, switch to a functional update and count drops out of the list. Watch identity, too. Objects, arrays and functions created during render are new on every render, so an options object in the array re-runs the effect every time. Build the object inside the effect, or depend on the primitives it's made from. And guard any state the effect sets: an effect that unconditionally updates a value it depends on will re-render and re-run forever.
For values the effect needs to read but shouldn't react to, use useEffectEvent. In this chat room, switching rooms should reconnect, but changing the theme shouldn't:
import { useEffect, useEffectEvent } from 'react';
const serverUrl = 'wss://chat.example.com';
function ChatRoom({ roomId, theme }) { const onConnected = useEffectEvent(() => { showNotification('Connected!', theme); });
useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.on('connected', () => onConnected()); connection.connect(); return () => connection.disconnect(); }, [roomId]);
return <h1>Welcome to {roomId}</h1>;}roomId stays in the array because a new room needs a new connection. theme doesn't need to be listed, since the Effect Event always sees its latest value. onConnected stays out as well: Effect Events aren't reactive, and you should only call them from inside effects.
Should you fetch data in useEffect?
You can, and for a single widget it's fine. But a raw fetch in an effect needs a guard against responses arriving out of order:
function Profile({ userId }) { const [user, setUser] = useState(null);
useEffect(() => { let ignore = false; fetch(`/api/users/${userId}`) .then(res => res.json()) .then(data => { if (!ignore) setUser(data); }); return () => { ignore = true; }; }, [userId]);
return user ? <h2>{user.name}</h2> : <p>Loading…</p>;}If userId switches from 1 to 2 and user 1's response lands last, cleanup has already flipped ignore for that run, so the stale profile can't overwrite the current one.
That fixes correctness and nothing else. Effects run after render, so a parent that fetches before rendering a child that also fetches creates a waterfall of sequential requests. Nothing is cached, so going back to a page refetches it. Effects don't run on the server, so server rendering ships a loading shell. And you're still hand-writing loading, error and retry state for every request.
For client-side data, TanStack Query or SWR handle caching, deduplication, race conditions and background revalidation for you. If you're on a framework, React Router loaders and Next.js server-side data fetching start requests before the component renders. React 19's use() can read a promise under Suspense, but the promise has to come from a cache or from outside the component. Create it during render and you start a new request on every render.
What useRef is really for
A ref is a mutable box that survives re-renders without causing any. useRef(initial) returns an object whose current property you can change freely, and React never notices. Use it for anything your logic needs to remember but the screen doesn't show: a setInterval ID you'll clear later, the previous value of a prop for an effect to compare against, a DOM node you want to focus. The catch is timing. Read and write ref.current in event handlers and effects, never during render. Output that depends on a ref won't update when the ref changes, and concurrent rendering makes mid-render mutations unpredictable.
React 19 makes refs easier to pass around. ref is now an ordinary prop on function components, so new code reads it from props and skips forwardRef. Ref callbacks can also return a cleanup function, which React calls when the node detaches. Attaching a ResizeObserver and disconnecting it can now live in one callback, with no checks for null.
Memoization in the React Compiler era
Your app should behave the same if you delete every useMemo, useCallback and React.memo in it. Memoization is a performance tool, and React's docs reserve the right to discard a cached value and recompute it. If removing a memo breaks something, such as an effect that suddenly loops, the bug lives elsewhere. Without the Compiler, record the slow interaction in the React Profiler first, find the component that re-renders too often or too slowly, and memoize only there. React.memo on a child also does nothing if the parent hands it a fresh object or inline function on every render, which is why the three tend to travel together.
React Compiler 1.0 changes the default. It analyzes your components at build time and inserts memoization for components and values automatically, so new useMemo and useCallback calls stop being a habit. Keep the ones you already have, since removing them can change what the compiler produces. They're still your escape hatch when you need a guarantee, for example giving an effect a dependency whose identity must stay stable.
The cost is setup. You need babel-plugin-react-compiler or your framework's integration, and components that break the Rules of React get skipped rather than optimized. What you get back is less code and more consistent results than hand memoization, which tends to be applied unevenly and goes stale as dependencies change.
Writing your own custom hooks
A custom hook shares logic, not state. Every component that calls it gets its own independent state, exactly as if you'd written those hook calls inline. Two components calling useOnlineStatus() don't share a variable. Each one subscribes separately and happens to get the same answer.
The name has to start with use. That prefix tells eslint-plugin-react-hooks to enforce the Rules of Hooks inside the function and wherever it's called. Name it getOnlineStatus and the linter won't catch someone calling it inside an if.
This hook wraps the browser's online and offline events with useSyncExternalStore, which handles subscribing, unsubscribing and reading the current value without an effect:
import { useSyncExternalStore } from 'react';
function subscribe(callback) { window.addEventListener('online', callback); window.addEventListener('offline', callback); return () => { window.removeEventListener('online', callback); window.removeEventListener('offline', callback); };}
export function useOnlineStatus() { return useSyncExternalStore( subscribe, () => navigator.onLine, // client snapshot () => true // server snapshot );}
function SaveButton() { const isOnline = useOnlineStatus(); return ( <button disabled={!isOnline}> {isOnline ? 'Save' : 'Reconnecting…'} </button> );}subscribe lives outside the hook so its identity stays stable. Define it inline and React resubscribes on every render. The server snapshot lets server rendering produce a value without touching navigator.
useMediaQuery is a natural next candidate, built on the same pattern with matchMedia change events. So is useLocalStorage, which pairs state with persistence. A hook that would only wrap a single useState call isn't worth extracting.
React 19 hooks for forms and data
React 19, stable since December 2024, moves mutations into "Actions": async functions you pass to startTransition or straight to a form's action prop. React tracks the pending state, catches errors, and resets uncontrolled form fields after a successful submit, so you write far fewer isLoading flags by hand.
useActionState replaces the canary-era useFormState. It takes your action and an initial state, and returns the latest state, a wrapped action to give the form, and isPending. Your action receives the previous state and the FormData. useFormStatus comes from react-dom, not react. It reads the pending state of the form it sits inside, so it only works in a child component of that form.
import { useActionState } from 'react';import { useFormStatus } from 'react-dom';
async function subscribe(prevState, formData) { const res = await fetch('/api/subscribe', { method: 'POST', body: formData }); return res.ok ? { error: null } : { error: 'Could not subscribe. Try again.' };}
function SubmitButton() { const { pending } = useFormStatus(); // reads the parent <form> return <button disabled={pending}>{pending ? 'Saving…' : 'Subscribe'}</button>;}
export function NewsletterForm() { const [state, formAction, isPending] = useActionState(subscribe, { error: null }); return ( <form action={formAction}> <input name="email" type="email" required disabled={isPending} /> <SubmitButton /> {state.error && <p role="alert">{state.error}</p>} </form> );}useOptimistic shows the result before the server confirms it. While the transition runs, the component renders the optimistic value; when it ends, the component falls back to real state. A failed request reverts on its own.
function LikeButton({ postId, initialLiked }) { const [liked, setLiked] = useState(initialLiked); const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
function toggle() { const next = !liked; startTransition(async () => { setOptimisticLiked(next); try { await saveLike(postId, next); setLiked(next); } catch { // no cleanup needed: the UI snaps back to `liked` } }); }
return <button onClick={toggle}>{optimisticLiked ? '♥ Liked' : '♡ Like'}</button>;}For reading data, use() accepts a promise or a context. Because it can be called conditionally, if (!user) return null; const theme = use(ThemeContext); is legal. Context also gets shorter: you can render <ThemeContext value="dark"> directly, and new code doesn't need <ThemeContext.Provider>.
Hooks for performance and edge cases
When every keystroke re-renders a heavy list and typing starts to lag, tell React which work can wait. useTransition marks a state update you trigger as non-urgent: startTransition(() => setTab('reports')) keeps the current screen responsive while the new one renders. useDeferredValue covers the case where you only have a value, such as input state or a prop:
function Search() { const [query, setQuery] = useState(''); const deferredQuery = useDeferredValue(query, ''); return ( <> <input value={query} onChange={e => setQuery(e.target.value)} /> <Results query={deferredQuery} /> </> );}The input updates immediately, and Results catches up when React has spare time. The second argument is React 19's initialValue: the first render uses '', then React renders the real value in the background.
useId produces IDs that match on server and client, so htmlFor, aria-describedby and similar attributes don't cause hydration mismatches. It isn't for list keys. Those should come from your data.
useSyncExternalStore subscribes a component to a store React doesn't own, like navigator.onLine. Zustand and Redux build on it, which is how they let a component subscribe to just the slice of state it needs.
useLayoutEffect runs before paint and blocks it. Use it only to measure layout, such as a tooltip's height, and reposition before the user sees a flicker. Everything else belongs in useEffect.
useImperativeHandle exposes a limited set of methods, say focus() and reset(), to a parent through a ref instead of the whole DOM node.
useInsertionEffect is for CSS-in-JS library authors injecting styles. App code doesn't need it.
Frequently Asked Questions
Can you use hooks inside a class component?
No. Hooks only work inside function components and custom hooks, and calling one in a class method throws an error. If you need a hook's logic in a class, wrap the class in a small function component that calls the hook and passes the result down as a prop. You don't have to rewrite everything at once, either. Classes are still supported and can live in the same tree as function components, so you can migrate one component at a time.
Should I use React Context or a state management library for global state?
Use Context for values that change rarely, like the theme, locale or signed-in user. Reach for a library like Zustand or Redux when shared state updates often. When a provider's value changes, every component that reads that context re-renders, even if it only cares about one field. Store libraries let each component subscribe to just the slice it uses, and they add devtools and middleware. A practical path is to start with useReducer plus Context, split contexts by concern, and switch only when re-renders actually hurt.
Set up your project to catch hook bugs
Most hook bugs can be caught before they ship. Install eslint-plugin-react-hooks, extend its recommended config, run the linter, and work through what it reports. The preset gives you rules-of-hooks, which flags a hook called inside a condition, loop or callback, and exhaustive-deps, which flags an effect that reads a value it doesn't list. It also includes the newer compiler-based rules, which catch patterns React Compiler can't safely optimize, such as reading ref.current during render. Set them to error rather than warn. Keep Strict Mode on in development too; the double mount is the cheapest way to find an effect with no cleanup.
For a new project, skip Create React App. It's deprecated, and react.dev now points people to Vite or to a framework like Next.js or React Router. If you choose Next.js, what Next.js 15 changed for React 19 and caching covers the framework side. Adding babel-plugin-react-compiler is optional. Turn it on and run your test suite. If everything passes, let the compiler handle memoization from then on.
Sources
- React Versions · react.dev
Want more from ScriptHill in Google? Add us as a preferred source



