Hook performance optimization?
Optimize hooks by avoiding work instead of caching it: derive values during render instead of syncing them with effects, keep state as local as possible, stabilize dependencies, split contexts, use transitions for heavy updates, and memoize only measured hot spots. With the React Compiler, most manual useMemo, useCallback and memo usage can be dropped.
Checklist
- Remove unnecessary effects: derived data computed in render avoids an extra render pass per change.
- Lazy initial state:
useState(() => expensive())runs the computation once. - Colocate state: fast-changing state (input text, hover) in the smallest component, so fewer components re-render.
- Stable dependencies: move objects and functions inside effects, depend on primitives, use updater functions, and
useEffectEventfor non-reactive logic. - Context: memoize provider values and split contexts by update frequency. For large global state, use a store with selectors (Zustand, Redux) so components subscribe to slices.
- Transitions:
useTransitionanduseDeferredValuekeep typing responsive during heavy renders. - Memoization:
useMemofor measured expensive computations,useCallback+memofor expensive children. - Avoid creating components inside components (remounts and lost state).
- Virtualize long lists.
- Debounce or throttle high-frequency events (scroll, resize, typing that triggers fetches).
React Compiler
Version 1.0 memoizes automatically at build time. Enable it via the Vite react-compiler-ts template, babel-plugin-react-compiler, or reactCompiler: true in Next.js, and use the eslint-plugin-react-hooks compiler rules to find code it cannot optimize.
Measure
Use the React DevTools Profiler and Chrome's React Performance tracks before and after changes.
Code example
1import { useDeferredValue, useMemo, useState } from "react";23type Product = { id: string; name: string; price: number };45export function Catalog({ products }: { products: Product[] }) {6 const [query, setQuery] = useState("");7 const [sort, setSort] = useState<"asc" | "desc">("asc");8 const deferredQuery = useDeferredValue(query); // typing stays responsive910 // Derived in render (memoized because the list is large); no effect + state pair11 const visible = useMemo(() => {12 const q = deferredQuery.toLowerCase();13 const filtered = products.filter((p) => p.name.toLowerCase().includes(q));14 return filtered.toSorted((a, b) => (sort === "asc" ? a.price - b.price : b.price - a.price));15 }, [products, deferredQuery, sort]);1617 return (18 <div>19 <input value={query} onChange={(e) => setQuery(e.target.value)} />20 <button onClick={() => setSort((s) => (s === "asc" ? "desc" : "asc"))}>Price {sort}</button>21 <p>{visible.length} products</p>22 </div>23 );24}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.