React Hooks Recipes

Practical React Hooks recipes for UI interactions, timers, measurement, polling, and optimistic updates.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

UI Recipes

High-value day-to-day React hook recipes.

Focus an input on mount

Use a ref and an effect to focus an input after mount.

tsxANYreacthooksfocususeRef
tsx
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
  inputRef.current?.focus();
}, []);
Notes

Simple and common autofocus pattern.

Build an interval counter

Update state on an interval with cleanup.

tsxANYreacthookstimersuseEffect
tsx
const [seconds, setSeconds] = useState(0);
useEffect(() => {
  const id = setInterval(() => setSeconds(s => s + 1), 1000);
  return () => clearInterval(id);
}, []);
Notes

Uses the updater form to avoid stale state issues.

Mirror a prop into state only when necessary

Initialize from props, then manage locally.

tsxANYreacthooksderived-stateuseEffect
tsx
const [draftName, setDraftName] = useState(name);
useEffect(() => {
  setDraftName(name);
}, [name]);
Notes

Use sparingly; derived state is often avoidable.

Measure an element’s size

Use a ref plus ResizeObserver.

tsxANYreacthooksResizeObservermeasurement
tsx
useEffect(() => {
  if (!ref.current) return;
  const observer = new ResizeObserver(([entry]) => {
    setSize(entry.contentRect);
  });
  observer.observe(ref.current);
  return () => observer.disconnect();
}, []);
Notes

A practical measurement pattern for responsive components.

Network and Server Recipes

Common data loading and request coordination patterns.

Polling with effect cleanup

Periodically refresh data until unmount.

tsxANYreacthookspollinguseEffect
tsx
useEffect(() => {
  let stopped = false;
  async function load() {
    const data = await fetch('/api/status').then(r => r.json());
    if (!stopped) setStatus(data);
  }
  load();
  const id = setInterval(load, 5000);
  return () => {
    stopped = true;
    clearInterval(id);
  };
}, []);
Notes

Polling needs cleanup and race awareness.

Optimistic UI with transition

Apply urgent optimistic state and schedule reconciliation.

tsxANYreacthooksuseTransitionoptimistic-ui
tsx
const [isPending, startTransition] = useTransition();
function handleAdd(todo: Todo) {
  setTodos(prev => [...prev, todo]);
  startTransition(async () => {
    await saveTodo(todo);
    refreshTodos();
  });
}
Notes

Transitions can keep follow-up updates non-blocking while the immediate optimistic UI stays responsive.

Recommended next

No recommendations yet.