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)
- Move state down: put the input's state inside the input component.
- Lift content up: a stateful wrapper that receives
childrendoes not re-render them when its state changes. - Split components so expensive parts do not share state with fast-changing parts.
- Split contexts by concern and update frequency.
- Selectors for global stores:
useStore((s) => s.user.name). - Derive, do not sync: compute values during render instead of setting state in effects.
- Stable keys to avoid remounts.
Memoization
memo(Component)skips rendering when props are shallowly equal.useMemofor objects or arrays passed as props;useCallbackfor 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/useTransitionlet heavy re-renders happen without blocking input.- Virtualize long lists so re-renders touch fewer rows.
Code example
tsx
1import { useState } from "react";23function ExpensiveTree() {4 console.log("ExpensiveTree render");5 return <div>Lots of UI…</div>;6}78// Before: every mouse move re-renders ExpensiveTree9// 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// }1415// After: state moved into a wrapper, content passed as children16function 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}2526export 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.