useState: render snapshots and the Rules of Hooks
import { useState } from "react";
export function QuantityPicker() {
const [quantity, setQuantity] = useState(1);
function addThree() {
setQuantity((previous) => previous + 1);
setQuantity((previous) => previous + 1);
setQuantity((previous) => previous + 1);
}
return (
<button type="button" onClick={addThree}>
Quantity: {quantity} (+3)
</button>
);
}
Each render sees a snapshot of state. Calling a setter schedules an update rather than changing the variable already captured by the current code. Three calls to setQuantity(quantity + 1) using the same snapshot do not add three; three pure functional updaters, as below, are applied in sequence. Replace objects and arrays rather than mutating state. [3]
Call hooks at the top level of a component or custom hook, before conditional returns, not in loops or event handlers. React associates hook state with call order. The resource-reading use API is an exception that permits loops and conditions but not try/catch. Enable the rules-of-hooks lint. [1][16][18]
useReducer: centralize state transitions
import { useReducer } from "react";
const initialState = { quantity: 1, unitPrice: 25 };
export function cartReducer(state, action) {
switch (action.type) {
case "add":
return { ...state, quantity: state.quantity + 1 };
case "remove":
return { ...state, quantity: Math.max(1, state.quantity - 1) };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export function Cart() {
const [cart, dispatch] = useReducer(cartReducer, initialState);
const total = cart.quantity * cart.unitPrice;
return (
<div>
<button type="button" onClick={() => dispatch({ type: "remove" })}>
Remove
</button>
<output>{total}</output>
<button type="button" onClick={() => dispatch({ type: "add" })}>
Add
</button>
</div>
);
}
When several events change related fields, a reducer collects update rules in a pure function. The cart quantity cannot go below one. Each action describes an event; the reducer calculates the next state without mutation, HTTP requests or other side effects. [4]
The total is derived from quantity and price, so it does not need its own state. This avoids inconsistent values. A simple toggle still works well with useState; use a reducer when explicit transitions make complex update logic clearer and independently testable.
useEffect: synchronize with an external system
import { useEffect, useState } from "react";
export function Timer({ running }) {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
if (!running) {
return;
}
const intervalId = window.setInterval(() => {
setSeconds((previous) => previous + 1);
}, 1000);
return () => {
window.clearInterval(intervalId);
};
}, [running]);
return <output>{seconds} s</output>;
}
A timer is a browser resource, so the effect creates it and cleanup releases it. Changing running cleans up the previous effect before setting up the new one; unmounting also triggers cleanup. In development, Strict Mode can exercise an additional setup, cleanup, setup cycle. [5]
Do not use an effect to calculate a total, filter a list or respond to a click. Derive values during rendering and handle user-triggered actions in event handlers. Dependencies follow the reactive values read by the effect, not a desired schedule. This timer counts callbacks rather than accurately measuring wall-clock time. [5][6]
useRef and useId: DOM access and accessibility
import { useId, useRef } from "react";
export function SearchField() {
const inputId = useId();
const inputRef = useRef(null);
function focusInput() {
inputRef.current?.focus();
}
return (
<div>
<label htmlFor={inputId}>Search</label>
<input id={inputId} ref={inputRef} type="search" />
<button type="button" onClick={focusInput}>
Focus search
</button>
</div>
);
}
useRef preserves a reference object across renders. Updating current does not trigger a render. Use it for DOM handles, timer identifiers or values that do not determine the displayed output. If a value needs to appear on screen, prefer state. Avoid reading or writing current during rendering except for predictable initialization. [7]
In the example, useId connects a label to its search field even if several instances are present. It is not a list key generator: use identifiers from the data for keys. Moving focus responds to a click, so it belongs in the handler rather than an effect. [8]
useContext: share data through the component tree
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext("light");
function ThemeLabel() {
const theme = useContext(ThemeContext);
return <p>Theme: {theme}</p>;
}
export function ThemePanel() {
const [theme, setTheme] = useState("light");
function toggleTheme() {
setTheme((previous) => (previous === "light" ? "dark" : "light"));
}
return (
<ThemeContext.Provider value={theme}>
<button type="button" onClick={toggleTheme}>
Switch theme
</button>
<ThemeLabel />
</ThemeContext.Provider>
);
}
Context reads the nearest matching provider without passing props through every intermediate component. The example supplies a simple theme identifier using .Provider, which also works with React 18. React 19 allows the context object itself to act as the provider. [9]
A changed provider value updates subscribing consumers; React compares values with Object.is. Creating a new object on every render can therefore cause unnecessary work. Consider separating values that update at different rates when measurements justify it. Context by itself does not provide a server-data cache.
useMemo, useCallback and memo: optimization, not correctness
import { memo, useCallback, useMemo, useState } from "react";
const ProductList = memo(function ProductList({ products, onSelect }) {
return (
<ul>
{products.map((product) => (
<li key={product.id}>
<button type="button" onClick={() => onSelect(product.id)}>
{product.name}
</button>
</li>
))}
</ul>
);
});
export function Catalog({ products, query }) {
const [selectedId, setSelectedId] = useState(null);
const visibleProducts = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase();
return products.filter((product) =>
product.name.toLowerCase().includes(normalizedQuery),
);
}, [products, query]);
const selectProduct = useCallback((productId) => {
setSelectedId(productId);
}, []);
return (
<div>
<p>Selected: {selectedId ?? "None"}</p>
<ProductList products={visibleProducts} onSelect={selectProduct} />
</div>
);
}
useMemo caches a calculated value and useCallback caches a function reference while dependencies remain unchanged. memo can skip child rendering when props stay equal. In the catalog, stable list and callback references can avoid rendering the product list when only the selected product changes. [10][11]
If a parent creates a fresh products array every time, the filter cache misses. Profile before adding complexity. React may discard cached values, so correctness must not depend on memoization. React Compiler can reduce the need for manual memoization in projects that enable it.
useDeferredValue and useTransition: render priorities
import { memo, useDeferredValue, useState } from "react";
const SearchResults = memo(function SearchResults({ products, query }) {
const normalizedQuery = query.trim().toLowerCase();
const matches = products.filter((product) =>
product.name.toLowerCase().includes(normalizedQuery),
);
return (
<ul>
{matches.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
});
export function ProductSearch({ products }) {
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<div>
<label>
Search products
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</label>
<div aria-busy={isStale}>
<SearchResults products={products} query={deferredQuery} />
</div>
</div>
);
}
A search field must reflect typing immediately, while expensive results can briefly reflect an older query. useDeferredValue allows React to defer less urgent rendering. Memoizing the results component helps it skip work with unchanged props during urgent updates. [12]
useTransition marks controlled state updates as non-urgent and provides isPending; do not use it for the state controlling a text input. Neither hook guarantees a fixed delay, debounces requests or moves computation to a Web Worker. A costly synchronous filter can still block the main thread. [13]
Custom hooks and useSyncExternalStore
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;
}
export function useOnlineStatus() {
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
export function ConnectionStatus() {
const isOnline = useOnlineStatus();
return <p role="status">{isOnline ? "Online" : "Offline"}</p>;
}
A custom hook extracts logic that uses hooks, but each call has independent state unless it reads a shared source. For external subscriptions, React provides useSyncExternalStore. The adapter below subscribes to connectivity events, removes listeners on unsubscribe and supplies a state snapshot. [14][15]
Here getServerSnapshot returns a conventional true for SSR and hydration, not a network measurement. navigator.onLine does not guarantee that a specific API is reachable. Other specialized APIs include useLayoutEffect for measurements before paint and, in supported React versions, useEffectEvent for non-reactive effect logic; it must not be used to conceal dependencies. [2][17]
