react, react-hooks, javascript, frontend
React Hooks Explained - State, Effects, Performance, Forms and Custom Hooks
A practical guide to every built-in React 19 hook, from useState and useEffect to use, useActionState, and useEffectEvent, with real-world JSX examples, custom hooks, and the rules of hooks.
Hooks are functions that let you use React features such as state, context, and side effects from function components. Before they existed, that work lived in class components, or was shared through higher-order components and render props. Hooks were proposed in 2018 and shipped as a stable API in React 16.8 in February 2019.
The first release included useState, useEffect, useContext, useReducer, useRef, useMemo, useCallback, useLayoutEffect, useImperativeHandle, and useDebugValue. React 18 (March 2022) added useTransition, useDeferredValue, useId, useSyncExternalStore, and useInsertionEffect. React 19 (December 2024) added the use API, useActionState, useOptimistic, and useFormStatus. React 19.2 (October 2025) added the stable useEffectEvent hook.
This article covers those built-in hooks as they exist in React 19, plus custom hooks and the rules every hook must follow. Each hook has a real-world JavaScript or JSX example. A shorter table of the original ten hooks is in a separate post.
Why Hooks Exist
Class components mixed rendering with lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. Related logic was often split across those methods, and unrelated logic was often packed into the same one. Reusing stateful behavior meant higher-order components or render props, which added wrappers and made the tree harder to follow.
Hooks address those problems in three ways:
- They let a function component hold state and subscribe to external systems without becoming a class.
- They let you split logic by concern, instead of by lifecycle method, and move it into a custom hook.
- They avoid the
thisbinding issues and boilerplate that class components accumulated.
Hooks did not remove class components. Existing classes still work, but new UI code usually uses hooks.
The Rules of Hooks
Hooks rely on being called in the same order on every render. React associates hook state with the call position, not with a name. That leads to two rules, enforced by eslint-plugin-react-hooks:
- Only call hooks at the top level of a function component or a custom hook. Do not call them inside loops, conditions, or nested functions.
- Only call hooks from React function components or from custom hooks. Do not call them from plain JavaScript functions, class components, or event handlers.
If you need hook state under a condition, extract a child component and put the hook there. The condition decides whether to render the child, and the child's hooks always run when that child is rendered.
The same rules apply to every hook in this article, including newer ones such as useActionState and useEffectEvent. The use API is the exception: despite its name, use is not a hook, and it may be called inside conditions and loops.
How Hooks Work
A render is a snapshot. The component function runs, reads props and state, and returns JSX. React then commits those changes to the DOM. Updating state schedules a new snapshot. Updating a ref does not.
Effects are how a component talks to systems React does not manage: the network, the DOM, a widget, a store, or a subscription. They run after render, at different times:
render (compute JSX)
|
v
useInsertionEffect // before React writes to the DOM
|
v
React updates the DOM
|
v
useLayoutEffect // after DOM updates, before the browser paints
|
v
browser paints
|
v
useEffect // after paint
Use useState or useReducer for values that affect the UI, useRef for values that should not trigger a render, and useEffect only to synchronize with something outside React. If you can compute a value from props or state during render, you do not need an Effect to store it.
State Hooks
useState
useState declares a state variable and a setter. Calling the setter queues a re-render with the new value. Pass a function to the setter when the next value depends on the previous one, so React applies updates in order even if several setters run in the same event. Pass a function as the initial value when initialization is expensive; React calls it only on the first render.
For example:
import { useState } from "react";
function QuantityPicker({ max = 10 }) {
const [quantity, setQuantity] = useState(1);
return (
<div>
<button type="button" onClick={() => setQuantity((q) => Math.max(1, q - 1))} disabled={quantity === 1}>
-
</button>
<span>{quantity}</span>
<button type="button" onClick={() => setQuantity((q) => Math.min(max, q + 1))} disabled={quantity === max}>
+
</button>
</div>
);
}
useReducer
useReducer is an alternative to useState when updates follow a clear set of actions, or when the next state depends on the previous state in several ways. You provide a reducer ((state, action) => nextState) and a dispatch function. Dispatching does not run the reducer in your event handler. React runs it during the next render.
For example:
import { useReducer } from "react";
function cartReducer(cart, action) {
switch (action.type) {
case "add": {
const existing = cart.find((item) => item.id === action.item.id);
if (existing) {
return cart.map((item) =>
item.id === action.item.id
? { ...item, quantity: item.quantity + 1 }
: item
);
}
return [...cart, { ...action.item, quantity: 1 }];
}
case "clear":
return [];
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function Cart() {
const [cart, dispatch] = useReducer(cartReducer, []);
const total = cart.reduce((sum, item) => sum + item.quantity, 0);
return (
<section>
<p>{total} items</p>
<button type="button" onClick={() => dispatch({ type: "add", item: { id: "sku-1", name: "Notebook" } })}>
Add notebook
</button>
<button type="button" onClick={() => dispatch({ type: "clear" })}>Clear cart</button>
</section>
);
}
useReducer helps when you want the update rules in one place, or when you want to test those rules without rendering the component.
useOptimistic
useOptimistic, added in React 19, lets you show a temporary value while an Action or Transition is in progress. You pass the confirmed state, and optionally a reducer that combines it with an optimistic update. The UI reads the optimistic value until the async work finishes, then settles on the confirmed state. If the Action fails and that state does not change, the optimistic value is discarded.
For example, a comment can appear before the server responds:
import { useOptimistic, useRef } from "react";
function CommentThread({ comments, onAddComment }) {
const formRef = useRef(null);
const [optimisticComments, addOptimistic] = useOptimistic(
comments,
(current, next) => [...current, next]
);
async function submitComment(formData) {
const text = String(formData.get("text") ?? "").trim();
if (!text) return;
addOptimistic({ id: `temp-${Date.now()}`, text, pending: true });
formRef.current?.reset();
await onAddComment(text);
}
return (
<section>
<ul>
{optimisticComments.map((comment) => (
<li key={comment.id} aria-busy={comment.pending || undefined}>
{comment.text}
</li>
))}
</ul>
<form ref={formRef} action={submitComment}>
<textarea name="text" required />
<button type="submit">Post comment</button>
</form>
</section>
);
}
Call addOptimistic from an Action or from startTransition. A plain event handler is not enough, because React needs the pending Transition to know when to fall back.
Context Hooks
useContext
useContext reads the closest context Provider above the component and subscribes to it. When the Provider's value changes, every consumer re-renders. This is the built-in way to share a theme, locale, or current user without passing props through every intermediate component.
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext(null);
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const value = { theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) };
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
function ThemedPanel() {
const { theme, toggle } = useContext(ThemeContext);
return (
<section data-theme={theme}>
<p>Current theme: {theme}</p>
<button type="button" onClick={toggle}>Toggle theme</button>
</section>
);
}
A common mistake is putting an object or function in value that is recreated on every render of the Provider, which re-renders every consumer even when the data did not change. Memoize the value, or split frequently changing data into a separate context.
If you need to read context inside a condition, use the use API described later.
Ref Hooks
useRef
useRef holds a mutable value that persists across renders and does not trigger a re-render when it changes. Typical uses are a DOM node, a timeout ID, or any mutable box you would have stored on this in a class.
Focusing an input when a modal opens is a common pattern:
import { useEffect, useRef } from "react";
function EditNameModal({ open, initialName, onClose, onSave }) {
const inputRef = useRef(null);
useEffect(() => {
if (open) {
inputRef.current?.focus();
}
}, [open]);
if (!open) return null;
return (
<dialog open onClose={onClose}>
<form
onSubmit={(event) => {
event.preventDefault();
onSave(inputRef.current.value);
onClose();
}}
>
<label>
Display name
<input ref={inputRef} defaultValue={initialName} />
</label>
<button type="submit">Save</button>
</form>
</dialog>
);
}
inputRef.current is the DOM node after React commits, so read it in an Effect or an event handler, not during the first render before the node exists. Prefer controlled useState when the UI must react to each keystroke. Use a ref, or an uncontrolled input with defaultValue, when you only need the value at submit time.
useImperativeHandle
useImperativeHandle customizes the instance a parent receives through a ref. Instead of exposing a DOM node, you expose a small set of methods. This is uncommon in application code, but useful when a reusable component needs an imperative API such as focus(), reset(), or scrollTo().
In React 19, ref is a regular prop, so you do not need forwardRef:
import { useImperativeHandle, useRef } from "react";
function SearchField({ ref, placeholder }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
},
clear() {
if (inputRef.current) inputRef.current.value = "";
},
}));
return <input ref={inputRef} type="search" placeholder={placeholder} />;
}
function HeaderSearch() {
const searchRef = useRef(null);
return (
<>
<SearchField ref={searchRef} placeholder="Search docs" />
<button type="button" onClick={() => searchRef.current?.focus()}>
Focus search
</button>
</>
);
}
If the parent can do the same work with a callback prop or with state, prefer that. Imperative handles are an escape hatch, not a substitute for data flowing down and events flowing up.
Effect Hooks
useEffect
useEffect connects a component to an external system. You return a cleanup function to undo that connection when the dependencies change or the component unmounts. The Effect runs after the browser paints. If you are not talking to an external system, you may not need an Effect at all.
Fetching a resource and canceling it when the id changes, or when the component unmounts, is the classic case:
import { useEffect, useState } from "react";
function ProductDetails({ productId }) {
const [product, setProduct] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
async function load() {
setError(null);
try {
const response = await fetch(`/api/products/${productId}`, {
signal: controller.signal,
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
setProduct(await response.json());
} catch (err) {
if (err.name !== "AbortError") setError(err);
}
}
load();
return () => controller.abort();
}, [productId]);
if (error) return <p>Could not load this product.</p>;
if (!product) return <p>Loading...</p>;
return <h2>{product.name}</h2>;
}
List every value from the component scope that the Effect reads in the dependency array, except stable setters from useState and functions returned by useEffectEvent. Skipping a dependency makes the Effect see stale props or state. If adding a dependency causes the Effect to re-run too often, move the value out, split the Effect, or extract a non-reactive event with useEffectEvent. Do not delete the dependency to silence the warning.
useLayoutEffect
useLayoutEffect has the same signature as useEffect, but it runs synchronously after React updates the DOM and before the browser paints. Use it when you must measure layout and adjust the UI in the same frame, so the user does not see a flicker.
A tooltip that flips above or below its target is a typical case:
import { useLayoutEffect, useRef, useState } from "react";
function Tooltip({ anchor, children }) {
const tooltipRef = useRef(null);
const [offsetY, setOffsetY] = useState(8);
useLayoutEffect(() => {
const el = tooltipRef.current;
if (!el || !anchor) return;
const height = el.getBoundingClientRect().height;
const fitsBelow = anchor.bottom + height + 8 < window.innerHeight;
setOffsetY(fitsBelow ? 8 : -(height + 8));
}, [anchor]);
return (
<div
ref={tooltipRef}
style={{ position: "fixed", top: anchor.bottom + offsetY, left: anchor.left }}
>
{children}
</div>
);
}
useLayoutEffect does not run on the server, and React warns if you use it in a component that is server-rendered. Prefer useEffect when a frame of delay is acceptable, such as focusing an input. Save layout Effects for measurements that must stay in sync with the paint.
useInsertionEffect
useInsertionEffect runs even earlier, before React writes to the DOM. It exists for CSS-in-JS libraries that need to inject stylesheets so DOM updates in the same commit already see the right rules. Application code should almost never use it. You cannot read layout here, and you should not subscribe to stores here.
A library might insert a rule like this:
import { useInsertionEffect } from "react";
function useStylesheet(css) {
useInsertionEffect(() => {
const style = document.createElement("style");
style.textContent = css;
document.head.appendChild(style);
return () => style.remove();
}, [css]);
}
useEffectEvent
useEffectEvent became a stable hook in React 19.2. It lets you extract the "event" part of an Effect: logic that should read the latest props and state when it runs, but should not retrigger the Effect when those values change.
Without it, a value such as a notification preference often ends up in the Effect's dependency list, and a change to that preference reconnects a socket. With useEffectEvent, the subscription depends only on the values that define the connection:
import { useEffect, useEffectEvent } from "react";
function CollabRoom({ roomId, notifyWithSound }) {
const onJoined = useEffectEvent((userName) => {
if (notifyWithSound) {
playJoinSound();
}
showToast(`${userName} joined ${roomId}`);
});
useEffect(() => {
const connection = createRoomConnection(roomId);
connection.on("joined", (user) => onJoined(user.name));
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <div>Connected to {roomId}</div>;
}
Do not put the function returned by useEffectEvent in a dependency array. Its identity is intentionally not stable. Do not call it during render, from a click handler, or pass it to a child. Call it only from Effects or from other Effect Events in the same component. Do not wrap arbitrary Effect logic in it just to silence the linter. If a value is part of the synchronization, it belongs in the dependency list.
Performance Hooks
useMemo
useMemo caches the result of a calculation between renders and recomputes it only when a dependency changes. Use it for work that is actually expensive, or to keep a stable object identity that a later Effect or a memoized child depends on.
import { useMemo, useState } from "react";
function InvoiceList({ invoices, status }) {
const [query, setQuery] = useState("");
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
return invoices.filter((invoice) => {
const matchesStatus = invoice.status === status;
const matchesQuery = q.length === 0 || invoice.customer.toLowerCase().includes(q);
return matchesStatus && matchesQuery;
});
}, [invoices, query, status]);
return (
<section>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter by customer" />
<p>{visible.length} invoices</p>
</section>
);
}
If the calculation is cheap, skip useMemo. React Compiler, when enabled, can memoize many of these cases automatically.
useCallback
useCallback caches a function definition. It is a convenience for useMemo(() => fn, deps). The usual reason to use it is to pass a stable callback to a child wrapped in React.memo, or to use a function as an Effect dependency without retriggering the Effect on every render.
import { memo, useCallback, useState } from "react";
const ItemRow = memo(function ItemRow({ item, onSelect }) {
return (
<button type="button" onClick={() => onSelect(item.id)}>
{item.name}
</button>
);
});
function ItemPicker({ items }) {
const [selectedId, setSelectedId] = useState(null);
const handleSelect = useCallback((id) => setSelectedId(id), []);
return (
<ul>
{items.map((item) => (
<ItemRow key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
);
}
A new inline function on every render is fine when the child is not memoized. Wrapping every handler in useCallback does not make a page faster by itself. Measure first.
useTransition
useTransition lets you mark a state update as a non-blocking Transition. React can keep the UI responsive, for example by continuing to update an input, and apply the expensive update in the background. It returns isPending and startTransition.
A catalog page that filters a large list on each keystroke is a good candidate:
import { useState, useTransition } from "react";
function Catalog({ products }) {
const [input, setInput] = useState("");
const [query, setQuery] = useState("");
const [isPending, startTransition] = useTransition();
function handleChange(event) {
const next = event.target.value;
setInput(next);
startTransition(() => setQuery(next));
}
const results = products.filter((product) =>
product.name.toLowerCase().includes(query.toLowerCase())
);
return (
<section>
<input value={input} onChange={handleChange} placeholder="Search products" />
{isPending && <p>Updating results...</p>}
<ul>
{results.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</section>
);
}
Keep the urgent update, such as the input text, outside the Transition. Put the heavy update, such as the query that drives a large list, inside startTransition. Newer updates can interrupt a Transition, which is what keeps typing smooth.
useDeferredValue
useDeferredValue is a related tool. Instead of splitting state yourself, you pass a value and React returns a deferred version that may lag behind during urgent updates. This is useful when an expensive child receives a value you do not control, such as a query prop.
import { useDeferredValue, useState } from "react";
function SearchPage({ documents }) {
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<section>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<SearchResults documents={documents} query={deferredQuery} />
</div>
</section>
);
}
React 19 accepts an optional initial value as the second argument. Choose useTransition when you own the setter. Choose useDeferredValue when you only have the value, not the setter.
Other Built-in Hooks
useId
useId generates a unique ID that is stable across the server render and the client hydrate. Use it to connect a label to an input, or to wire aria-describedby and similar attributes, without hard-coding IDs that might clash if the component appears twice.
import { useId, useState } from "react";
function EmailField() {
const id = useId();
const hintId = `${id}-hint`;
const [email, setEmail] = useState("");
return (
<div>
<label htmlFor={id}>Email</label>
<input
id={id}
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-describedby={hintId}
/>
<p id={hintId}>We will use this to send your receipt.</p>
</div>
);
}
Do not use useId to produce keys for a list. Keys should come from your data. The string it returns may contain characters such as :, so prefer it for accessibility attributes rather than as a general-purpose unique key.
useSyncExternalStore
useSyncExternalStore is the safe way to subscribe a component to a store that lives outside React, such as a browser API or a library store. It takes subscribe, getSnapshot, and, for server rendering, getServerSnapshot. React 18 introduced it so concurrent rendering does not tear: the component always sees a consistent snapshot between render and the later subscription.
A hook that tracks the online status of the browser looks like this:
import { useSyncExternalStore } from "react";
function subscribe(onStoreChange) {
window.addEventListener("online", onStoreChange);
window.addEventListener("offline", onStoreChange);
return () => {
window.removeEventListener("online", onStoreChange);
window.removeEventListener("offline", onStoreChange);
};
}
function getSnapshot() {
return navigator.onLine;
}
function getServerSnapshot() {
return true;
}
function useOnlineStatus() {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
function SaveIndicator() {
const online = useOnlineStatus();
return <p>{online ? "Changes save automatically." : "You are offline."}</p>;
}
getSnapshot must return an immutable value, and the same value (by Object.is) if the store has not changed. Returning a new object every time will loop. Libraries such as React Redux use this hook internally.
useDebugValue
useDebugValue customizes the label React DevTools shows for a custom hook. It has no effect in the UI of your app. Call it only inside custom hooks, and optionally pass a formatter so the label work runs only when DevTools is open.
import { useDebugValue } from "react";
function useOnlineStatus() {
const online = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
useDebugValue(online ? "Online" : "Offline");
return online;
}
useActionState
useActionState, added in React 19, ties a piece of state to the result of an Action. You pass a reducer-like function and an initial state. The hook returns the current state, a wrapped Action, and an isPending flag. You can pass the wrapped Action to a form's action prop. The function receives the previous state and, for a form, the submitted FormData.
A profile form that posts a new display name looks like this:
import { useActionState } from "react";
async function updateDisplayName(previousState, formData) {
const name = String(formData.get("name") ?? "").trim();
if (name.length < 2) {
return { ok: false, message: "Name must be at least 2 characters.", name };
}
try {
await saveDisplayName(name);
return { ok: true, message: "Display name updated.", name };
} catch {
return { ok: false, message: "Could not save. Try again.", name };
}
}
function DisplayNameForm({ currentName }) {
const [state, formAction, isPending] = useActionState(updateDisplayName, {
ok: true,
message: "",
name: currentName,
});
return (
<form action={formAction}>
<label>
Display name
<input name="name" defaultValue={state.name} disabled={isPending} />
</label>
<button type="submit" disabled={isPending}>
{isPending ? "Saving..." : "Save"}
</button>
{state.message && <p role="status">{state.message}</p>}
</form>
);
}
This hook was called useFormState in early Canary releases and was renamed. useFormState is deprecated. The optional third argument, permalink, is for progressive enhancement with React Server Components.
If you call the wrapped Action from a click handler rather than from a form action prop, wrap that call in startTransition. Do not invoke the Action during render.
useFormStatus
useFormStatus lives in react-dom, not in react. It reads the submission status of the nearest parent <form>: pending, the FormData being submitted, the HTTP method, and the action function. Design-system components can use it to disable a button or show a spinner without extra props.
import { useFormStatus } from "react-dom";
function SubmitButton({ children }) {
const { pending, data } = useFormStatus();
const email = data?.get("email");
return (
<button type="submit" disabled={pending}>
{pending ? (email ? `Subscribing ${email}...` : "Subscribing...") : children}
</button>
);
}
function NewsletterForm({ subscribe }) {
return (
<form action={subscribe}>
<label>
Email
<input type="email" name="email" required />
</label>
<SubmitButton>Subscribe</SubmitButton>
</form>
);
}
The hook only sees a parent form. If you call it in the same component that renders the <form>, pending stays false. Move it into a child, as SubmitButton does above.
The use API
use lets a component read a resource during render: a Promise or a context. Despite its name, it is not a hook. You may call it inside conditions and loops, as long as you still call it from a component or a custom hook.
When you pass a Promise, the component suspends until the Promise resolves. A parent Suspense boundary shows its fallback in the meantime. If the Promise rejects, the nearest Error Boundary handles it. Do not wrap use in try / catch. Promises passed to use must be cached, so the same instance is reused across re-renders. Creating a new Promise during render, for example by calling fetch inline, will trigger a warning and can loop.
import { Suspense, use } from "react";
const articleCache = new Map();
function fetchArticle(id) {
if (!articleCache.has(id)) {
articleCache.set(
id,
fetch(`/api/articles/${id}`).then((response) => {
if (!response.ok) throw new Error("Article not found");
return response.json();
})
);
}
return articleCache.get(id);
}
function ArticleBody({ articlePromise }) {
const article = use(articlePromise);
return (
<article>
<h2>{article.title}</h2>
<p>{article.body}</p>
</article>
);
}
function ArticlePage({ articleId }) {
return (
<Suspense fallback={<p>Loading article...</p>}>
<ArticleBody articlePromise={fetchArticle(articleId)} />
</Suspense>
);
}
In a Server Component, you can often await the data and pass a cached Promise down to a Client Component that calls use.
use(ThemeContext) reads context and, unlike useContext, may sit behind an if. Reading context with use is not supported in Server Components. Prefer useContext when you always read the value at the top level.
Custom Hooks
A custom hook is a JavaScript function whose name starts with use and that may call other hooks. It is the supported way to reuse stateful logic. Calling a custom hook from two components gives each component its own state. Hooks share the logic, not the data.
A debounced search box is easier to follow when the debounce lives in a hook:
import { useEffect, useState } from "react";
function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timeoutId = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(timeoutId);
}, [value, delayMs]);
return debounced;
}
function UserSearch({ onSearch }) {
const [query, setQuery] = useState("");
const debouncedQuery = useDebouncedValue(query, 300);
useEffect(() => {
onSearch(debouncedQuery);
}, [debouncedQuery, onSearch]);
return (
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search users"
/>
);
}
Custom hooks can take arguments, return values, and call other hooks, as long as they follow the Rules of Hooks. Those hook calls count toward the call order of the component that uses the custom hook.
Build a custom hook when the same sequence appears in more than one component. Do not add a use prefix to a plain helper that never calls hooks. That misleads both readers and the lint rule.
Common Mistakes
- Calling hooks conditionally. Moving a
useStateoruseEffectcall behind anifbreaks the call order. Extract a component instead. - Using an Effect to copy props into state or to compute derived data. Calculate during render, or key a child so it resets when the source changes.
- Omitting Effect dependencies or disabling the lint rule to hide a warning. Stale closures follow. If a value should not retrigger the Effect, it may belong in
useEffectEvent, in a ref, or outside the Effect entirely. - Forgetting cleanup. A fetch without
AbortController, a subscription withoutunsubscribe, or asetTimeoutwithoutclearTimeoutcan update state after unmount or leak listeners. - Mutating state in place, then passing the same object or array back to the setter. React may skip the re-render because the reference did not change.
- Wrapping everything in
useMemoanduseCallback. Memoization is for measured, expensive work or for stable identities that matter, not a default wrapper. - Reaching for
useLayoutEffectby habit. It blocks paint and warns during server rendering. Use it when you must measure the DOM before the user sees it. - Using
useEffectEventto hide missing dependencies. The hook is for events fired from Effects, not for opting out of reactivity. - Calling
useFormStatusin the component that renders the form. The hook only sees a parent form. Move it into a child. - Calling
addOptimisticor auseActionStateAction outside a Transition. Formactionprops andstartTransitionset that context for you. - Passing an uncached Promise to
use, or wrappinguseintry/catch. Cache the Promise and let an Error Boundary handle failures. - Using
useIdas a list key, or usinguseRefwhen the UI needs to update in response to the value. Keys come from data. Values that affect rendering belong in state. - Creating a new object as a context Provider's
valueon every render, which re-renders every consumer. Stabilize the value or split the context.
Quick Reference
| Hook | Package | Since | Role |
|---|---|---|---|
useState |
react |
16.8 | Local state and a setter |
useEffect |
react |
16.8 | Sync with an external system after paint |
useContext |
react |
16.8 | Read context at the top level |
useReducer |
react |
16.8 | State updated through a reducer |
useCallback |
react |
16.8 | Cached function identity |
useMemo |
react |
16.8 | Cached calculation |
useRef |
react |
16.8 | Mutable ref that does not re-render |
useImperativeHandle |
react |
16.8 | Customize the ref a parent receives |
useLayoutEffect |
react |
16.8 | Effects after DOM updates, before paint |
useDebugValue |
react |
16.8 | DevTools label for a custom hook |
useTransition |
react |
18.0 | Non-blocking state updates |
useDeferredValue |
react |
18.0 | Deferred version of a value |
useId |
react |
18.0 | Hydration-safe unique ID |
useSyncExternalStore |
react |
18.0 | Subscribe to an external store |
useInsertionEffect |
react |
18.0 | Inject styles before DOM writes |
use |
react |
19.0 | Read a Promise or context during render (not a hook) |
useActionState |
react |
19.0 | State driven by an Action |
useOptimistic |
react |
19.0 | Temporary state during an Action |
useFormStatus |
react-dom |
19.0 | Parent form submission status |
useEffectEvent |
react |
19.2 | Non-reactive event called from an Effect |
The two rules stay the same: call hooks at the top level, and only from React functions or custom hooks. Enable eslint-plugin-react-hooks so those rules and the useEffectEvent restrictions are checked automatically.
Conclusion
Hooks are the usual way to use React features from function components. They started in React 16.8 as a replacement for much of the work that used to live in class lifecycles, and they have grown into a set of tools with clear jobs: state, context, refs, Effects, performance, external stores, and, in React 19, Actions, optimistic UI, and reading Promises during render.
Pick the hook that matches the job and no more. Use state for values the user should see change, a ref when a change should not redraw the screen, and an Effect only to synchronize with a system outside React. Use Transitions when a large update would otherwise block typing, and extract a custom hook when the same sequence of calls would otherwise be copied between components. Follow the Rules of Hooks, keep dependency lists honest, and treat newer APIs such as use, useActionState, useOptimistic, useFormStatus, and useEffectEvent according to the official documentation. The API is larger than it was in 2019, but each hook is still a small function with a specific role, and the original rules still hold.