ReactMedium

How to prevent re-renders?

Prevent wasteful re-renders by structuring state well first (keep it low, pass content as children, split contexts, subscribe to store slices), then memoizing where profiling shows a cost: memo for components, useMemo and useCallback for stable props, or the React Compiler to do all of it automatically.

Structural techniques (no memoization)

  1. Move state down: put the input's state inside the input component.
  2. Lift content up: a stateful wrapper that receives children does not re-render them when its state changes.
  3. Split components so expensive parts do not share state with fast-changing parts.
  4. Split contexts by concern and update frequency.
  5. Selectors for global stores: useStore((s) => s.user.name).
  6. Derive, do not sync: compute values during render instead of setting state in effects.
  7. Stable keys to avoid remounts.

Memoization

  • memo(Component) skips rendering when props are shallowly equal.
  • useMemo for objects or arrays passed as props; useCallback for function props.
  • Memoize context provider values.

Let the compiler do it

React Compiler 1.0 automatically memoizes components and values with fine granularity. Enable it with babel-plugin-react-compiler, Vite's react-compiler-ts template or Next.js reactCompiler: true. Then remove most manual memoization.

Not "prevent", but "make cheap"

  • useDeferredValue/useTransition let heavy re-renders happen without blocking input.
  • Virtualize long lists so re-renders touch fewer rows.

Code example

tsx
1import { useState } from "react";
2
3function ExpensiveTree() {
4 console.log("ExpensiveTree render");
5 return <div>Lots of UI…</div>;
6}
7
8// Before: every mouse move re-renders ExpensiveTree
9// export function Page() {
10// const [pos, setPos] = useState({ x: 0, y: 0 });
11// return <div onPointerMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
12// <p>{pos.x},{pos.y}</p><ExpensiveTree /></div>;
13// }
14
15// After: state moved into a wrapper, content passed as children
16function PointerTracker({ children }: { children: React.ReactNode }) {
17 const [pos, setPos] = useState({ x: 0, y: 0 });
18 return (
19 <div onPointerMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
20 <p>{pos.x}, {pos.y}</p>
21 {children} {/* same element object from the parent: not re-rendered */}
22 </div>
23 );
24}
25
26export function Page() {
27 return (
28 <PointerTracker>
29 <ExpensiveTree />
30 </PointerTracker>
31 );
32}

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.

Open in study app