const [count, setCount] = useState(0);Use `useState` when state updates are straightforward and local to a component.
Built-in React Hooks reference covering state, effects, refs, context, memoization, transitions, and store subscriptions.
Core state management hooks.
const [count, setCount] = useState(0);Use `useState` when state updates are straightforward and local to a component.
setCount(prev => prev + 1);Prefer the updater form when the next state depends on the previous state.
const [items, setItems] = useState(() => loadInitialItems());Pass a function to avoid recalculating expensive initial state on every render.
const [state, dispatch] = useReducer(reducer, initialState);`useReducer` is useful when state transitions are more complex or action-driven.
const [state, dispatch] = useReducer(reducer, initialArg, init);The third `init` argument lazily computes the initial reducer state.
const initialForm = { email: '', password: '' };
const [form, setForm] = useState(initialForm);
const resetForm = () => setForm(initialForm);Useful for form reset behavior after submit or cancel.
Synchronization and side effects.
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);Use effects to synchronize with external systems like DOM APIs, subscriptions, timers, and network calls.
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);Return a cleanup function to unsubscribe, cancel, or undo the effect on dependency change or unmount.
useLayoutEffect(() => {
inputRef.current?.focus();
}, []);Reserve `useLayoutEffect` for measurement or layout-sensitive updates; prefer `useEffect` by default.
useInsertionEffect(() => {
injectStyles(ruleText);
}, [ruleText]);Library-oriented hook for style injection use cases.
useEffect(() => {
let ignore = false;
fetch(`/api/users/${userId}`)
.then(r => r.json())
.then(data => { if (!ignore) setUser(data); });
return () => { ignore = true; };
}, [userId]);Guard against race conditions when multiple requests can finish out of order.
Read latest values in an effect event without re-triggering the effect.
const onVisit = useEffectEvent((visitedUrl: string) => {
logVisit(visitedUrl, cart.length);
});
useEffect(() => {
onVisit(url);
}, [url]);Use for event-like logic called from effects that should see fresh values.
Context consumption and imperative references.
const theme = useContext(ThemeContext);Use context to avoid repetitive prop drilling for shared values like theme, auth, locale, or configuration.
const inputRef = useRef<HTMLInputElement | null>(null);
inputRef.current?.focus();Refs are useful for DOM access, timers, imperative APIs, or mutable values that do not trigger re-renders.
const latestValue = useRef(value);
latestValue.current = value;Common for storing previous values, AbortControllers, or instance-like fields.
useImperativeHandle(ref, () => ({
focus: () => inputRef.current?.focus(),
clear: () => setValue(''),
}), []);Use with `forwardRef` when a parent truly needs an imperative child API.
const id = useId();
return <><label htmlFor={id}>Email</label><input id={id} /></>;Useful for accessibility when components need unique IDs that work consistently with server rendering.
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);
useDebugValue(isOnline ? 'Online' : 'Offline');
return isOnline;
}Primarily helpful in reusable hooks that appear in DevTools.
Memoization, deferred rendering, transitions, and external store subscriptions.
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);Use when a recalculation is expensive or when referential stability matters for child memoization.
const handleSubmit = useCallback(() => {
saveForm(form);
}, [form]);Useful when child components depend on stable callback identity.
const [isPending, startTransition] = useTransition();
startTransition(() => {
setQuery(nextQuery);
});Transitions help keep urgent interactions responsive while scheduling less urgent UI updates.
Defer a value so expensive children lag behind urgent input.
const deferredQuery = useDeferredValue(query);
const results = useMemo(() => search(items, deferredQuery), [items, deferredQuery]);Useful for search UIs where input should stay responsive even if results are expensive to compute.
Read and subscribe to an external store consistently.
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);For libraries or app code integrating with non-React stores while preserving concurrent rendering correctness.
const theme = use(ThemeContext);
const product = use(productPromise);The `use` API can read context or suspend on promises in supported React environments.