elefcode
← All cheat sheets

Languages

React Hooks Cheat Sheet — useState, useEffect, and More

Every built-in React hook you will use, what it is for, and the patterns and pitfalls that go with it.

Put it into practice with the matching tool.

Convert HTML to JSX →

Advertisement

State

const [n, setN] = useState(0)Local state with an initial value
setN(n => n + 1)Updater function — safe when the new value depends on the old
useState(() => expensive())Lazy initial value, computed only on the first render
setUser({ ...user, name })Replace objects; never mutate state in place
const [s, dispatch] = useReducer(reducer, init)State managed by a reducer function

Effects

useEffect(() => { ... }, [dep])Run after render when a dependency changes
useEffect(() => { ... }, [])Run once after the first render
return () => unsubscribe()Cleanup before the next run and on unmount
useLayoutEffect(fn, deps)Runs before paint — for measuring layout
const ac = new AbortController()Cancel a fetch in effect cleanup with ac.abort()

Refs

const ref = useRef(null)Mutable box that survives renders without causing one
<input ref={ref} />Get the DOM node in ref.current
ref.current = valueStore timers, previous values, or instances
useImperativeHandle(ref, () => api)Expose a custom API to a parent ref
const id = useId()Stable unique ID for label/input pairs

Context

const Ctx = createContext(defaultValue)Create a context
<Ctx value={v}>...</Ctx>Provide a value (React 19; Ctx.Provider before that)
const v = useContext(Ctx)Read the nearest provided value
const v = use(Ctx)React 19: read context or a promise, even conditionally

Performance

useMemo(() => compute(a), [a])Cache an expensive calculation
useCallback(fn, [deps])Keep a function identity stable between renders
memo(Component)Skip re-rendering when props are unchanged
const [isPending, startTransition] = useTransition()Mark an update as non-urgent
useDeferredValue(value)Let a slow render lag behind fast typing

Rules and forms

Top level onlyNever call hooks inside conditions, loops, or nested functions
function useThing() { ... }Custom hooks must start with "use"
useActionState(action, initial)React 19: state and pending flag for a form action
useOptimistic(state, update)React 19: show an optimistic value while an action runs
useSyncExternalStore(sub, get)Subscribe to an external store safely

Related guides

More cheat sheets