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
Focus an input on mount
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
  inputRef.current?.focus();
}, []);

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

Build an interval counter
const [seconds, setSeconds] = useState(0);
useEffect(() => {
  const id = setInterval(() => setSeconds(s => s + 1), 1000);
  return () => clearInterval(id);
}, []);

# Update state on an interval with cleanup.

Mirror a prop into state only when necessary
const [draftName, setDraftName] = useState(name);
useEffect(() => {
  setDraftName(name);
}, [name]);

# Initialize from props, then manage locally.

Measure an element’s size
useEffect(() => {
  if (!ref.current) return;
  const observer = new ResizeObserver(([entry]) => {
    setSize(entry.contentRect);
  });
  observer.observe(ref.current);
  return () => observer.disconnect();
}, []);

# Use a ref plus ResizeObserver.

## Network and Server Recipes
Polling with effect cleanup
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);
  };
}, []);

# Periodically refresh data until unmount.

Optimistic UI with transition
const [isPending, startTransition] = useTransition();
function handleAdd(todo: Todo) {
  setTodos(prev => [...prev, todo]);
  startTransition(async () => {
    await saveTodo(todo);
    refreshTodos();
  });
}

# Apply urgent optimistic state and schedule reconciliation.

Recommended next

No recommendations yet.