Hooks, Refs and State Patterns

useState, useReducer, useRef and custom hooks, plus the rules that keep hooks working correctly.

Intermediate · about 6 hours · difficulty 3/5

Learn first: React

Hooks are how function components remember things and reuse logic. They look like ordinary function calls, but React tracks them by call order, which is why the rules of hooks exist.

The rules

  1. Call hooks only at the top level of a component or custom hook, never inside conditions, loops or after an early return.
  2. Call them only from React functions. The eslint-plugin-react-hooks rules enforce both; keep them on.

State hooks

  • useState for independent values. Use the updater form setCount(c => c + 1) when the next value depends on the previous one.
  • useReducer when several values change together or transitions have names (dispatch({ type: "added", item })). A reducer is a pure function, easy to test.
  • Model state carefully: avoid redundant or contradictory state. A status: "idle" | "loading" | "error" beats three booleans.

Refs

useRef holds a mutable value that survives renders without causing re-renders. Use it for DOM nodes (focusing an input, measuring size), timers and the latest value of something. Do not read or write refs during rendering for things that affect output.

Custom hooks

Extract reusable stateful logic into functions named useSomething: useDebounce, useLocalStorage, useMediaQuery. Each component that calls a custom hook gets its own independent state.

Good enough to move on

You can refactor tangled useState calls into a reducer, focus an input with a ref, and write and reuse two custom hooks of your own.

Key concepts

  • Rules of hooks
  • useState updater functions
  • useReducer
  • Structuring state to avoid contradictions
  • useRef for DOM access and mutable values
  • Custom hooks
  • useId and other utility hooks

Mini project

Build a multi-step checkout form driven by useReducer, with a custom useLocalStorage hook to persist progress and a ref that focuses the first invalid field on submit.

Check yourself

Why does calling `setCount(count + 1)` three times in one click handler only increase count by one?

Free resources