ReactEasy

What are React Hooks?

Hooks are functions that start with use and let function components use React features: state (useState, useReducer), side effects (useEffect), context (useContext, use), refs (useRef), performance (useMemo, useCallback), concurrency (useTransition, useDeferredValue) and forms (useActionState, useOptimistic). You can also write your own custom hooks.

Built-in hooks by category

  • State: useState, useReducer.
  • Context: useContext, and use(Context) (React 19, can be called conditionally).
  • Refs: useRef, useImperativeHandle.
  • Effects: useEffect, useLayoutEffect, useInsertionEffect, useEffectEvent (React 19.2, for non-reactive logic inside effects).
  • Performance: useMemo, useCallback, useTransition, useDeferredValue.
  • Actions and forms (React 19): useActionState, useOptimistic, useFormStatus (from react-dom).
  • Other: useId, useSyncExternalStore, useDebugValue.
  • use(promise): read a promise or context during render, suspending until resolved.

Rules of Hooks

  1. Call hooks at the top level of a component or custom hook, not inside conditions, loops or nested functions (the use API is the exception).
  2. Call them only from React function components or custom hooks. eslint-plugin-react-hooks (v7) enforces these and adds React Compiler-powered rules.

Why they matter

Hooks let you reuse stateful logic across components without wrappers, keep related logic together, and are required by modern React features. Class components cannot use hooks.

Code example

tsx
1import { useEffect, useMemo, useRef, useState, useTransition } from "react";
2
3export function UserSearch({ users }: { users: { id: string; name: string }[] }) {
4 const [query, setQuery] = useState(""); // state
5 const [filter, setFilter] = useState("");
6 const [isPending, startTransition] = useTransition(); // concurrency
7 const inputRef = useRef<HTMLInputElement>(null); // ref
8
9 useEffect(() => { // effect
10 inputRef.current?.focus();
11 }, []);
12
13 const results = useMemo( // memoized value
14 () => users.filter((u) => u.name.toLowerCase().includes(filter.toLowerCase())),
15 [users, filter]
16 );
17
18 return (
19 <div>
20 <input
21 ref={inputRef}
22 value={query}
23 onChange={(e) => {
24 setQuery(e.target.value); // urgent: keep typing responsive
25 startTransition(() => setFilter(e.target.value)); // non-urgent: filtering
26 }}
27 />
28 {isPending && <span>Filtering…</span>}
29 <ul>{results.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
30 </div>
31 );
32}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app