React Hooks Cheat Sheet

Built-in React Hooks reference covering state, effects, refs, context, memoization, transitions, and store subscriptions.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## State Hooks
useState basic state
const [count, setCount] = useState(0);

# Create local component state.

useState updater function
setCount(prev => prev + 1);

# Update based on previous state safely.

useState lazy initializer
const [items, setItems] = useState(() => loadInitialItems());

# Compute expensive initial state once.

useReducer basic reducer
const [state, dispatch] = useReducer(reducer, initialState);

# Manage more structured state transitions.

useReducer with init function
const [state, dispatch] = useReducer(reducer, initialArg, init);

# Lazily derive reducer state.

Reset component state
const initialForm = { email: '', password: '' };
const [form, setForm] = useState(initialForm);
const resetForm = () => setForm(initialForm);

# Reset state back to initial values.

## Effect Hooks
useEffect after render
useEffect(() => {
  document.title = `Count: ${count}`;
}, [count]);

# Run side effects after React commits updates.

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

# Clean up subscriptions or listeners.

useLayoutEffect before paint
useLayoutEffect(() => {
  inputRef.current?.focus();
}, []);

# Run a layout-sensitive effect before the browser paints.

useInsertionEffect for CSS injection
useInsertionEffect(() => {
  injectStyles(ruleText);
}, [ruleText]);

# Insert styles before layout effects.

Fetch inside an effect
useEffect(() => {
  let ignore = false;
  fetch(`/api/users/${userId}`)
    .then(r => r.json())
    .then(data => { if (!ignore) setUser(data); });
  return () => { ignore = true; };
}, [userId]);

# Fetch client-side data in an effect with cleanup guard.

useEffectEvent for non-reactive effect logic
const onVisit = useEffectEvent((visitedUrl: string) => {
  logVisit(visitedUrl, cart.length);
});

useEffect(() => {
  onVisit(url);
}, [url]);

# Read latest values in an effect event without re-triggering the effect.

## Context and Ref Hooks
useContext basic usage
const theme = useContext(ThemeContext);

# Read the nearest context value.

useRef DOM reference
const inputRef = useRef<HTMLInputElement | null>(null);
inputRef.current?.focus();

# Reference a DOM node.

useRef mutable container
const latestValue = useRef(value);
latestValue.current = value;

# Persist mutable values between renders without re-rendering.

useImperativeHandle custom ref API
useImperativeHandle(ref, () => ({
  focus: () => inputRef.current?.focus(),
  clear: () => setValue(''),
}), []);

# Expose a controlled imperative API to a parent ref.

useId for stable accessible IDs
const id = useId();
return <><label htmlFor={id}>Email</label><input id={id} /></>;

# Generate stable IDs for labels and ARIA relationships.

useDebugValue in a custom hook
function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);
  useDebugValue(isOnline ? 'Online' : 'Offline');
  return isOnline;
}

# Label a custom hook in React DevTools.

## Performance and Concurrency Hooks
useMemo memoized derived value
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);

# Cache an expensive derived computation.

useCallback stable callback
const handleSubmit = useCallback(() => {
  saveForm(form);
}, [form]);

# Memoize a callback passed to children.

useTransition for non-urgent updates
const [isPending, startTransition] = useTransition();
startTransition(() => {
  setQuery(nextQuery);
});

# Mark updates as transitions.

useDeferredValue delay expensive rendering
const deferredQuery = useDeferredValue(query);
const results = useMemo(() => search(items, deferredQuery), [items, deferredQuery]);

# Defer a value so expensive children lag behind urgent input.

useSyncExternalStore subscribe to external state
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);

# Read and subscribe to an external store consistently.

use API with context or promise
const theme = use(ThemeContext);
const product = use(productPromise);

# Read context or promise values with the `use` API.

Recommended next

No recommendations yet.