ESC

Type to search the knowledge base.

Cheat sheetReact

React Hooks

useState, useEffect, useMemo, useCallback, useRef — mental models and footguns.

useState

tsx
const [count, setCount] = useState(0);
setCount(1);
setCount(c => c + 1); // functional — uses latest

// Lazy init for expensive initial state
const [data, setData] = useState(() => bigCompute());

useEffect

tsx
useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id); // cleanup
}, [tick]);

// []   → mount / unmount
// none → every render (rare; usually a smell)
// [x]  → when x changes by Object.is

useRef

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

// Mutable box that does NOT trigger re-render
const latest = useRef(value);
latest.current = value;

useMemo / useCallback

tsx
const filtered = useMemo(
  () => items.filter(predicate),
  [items, predicate]
);

const onSave = useCallback(() => {
  save(id);
}, [id]);

Rules of Hooks

  • ·Only call Hooks at the top level (no conditions/loops).
  • ·Only call Hooks from React functions (components or custom hooks).
  • ·Custom hooks start with use and may call other hooks.

Interview tips

  • Describe effects as sync with external systems, not “run this code”.
  • Explain stale closures and how deps/refs fix them.
  • Don’t memoize everything — know the cost model.

Common mistakes

  • !Missing cleanup → leaks and duplicate listeners.
  • !Empty deps with used props/state → stale values.
  • !Mutating state arrays/objects in place.
  • !Putting pure derived data in state instead of computing during render.

Related

← All cheat sheets