React Performance
React is fast by default, and most apps never need tuning. When an interface does feel slow, the cause is usually one of a few patterns: too much re-rendering, too much rendering at once, or too much JavaScript to download. This lesson collects the tools you've met in earlier chapters into a practical checklist.
Step 1: Measure first
Never optimize by guessing. Use:
| Tool | Shows |
|---|---|
| React DevTools → Profiler | which components rendered, why, and how long they took |
| React DevTools → "Highlight updates" | flashes components as they re-render |
| Browser DevTools → Performance | long tasks blocking the main thread |
| Lighthouse / Web Vitals | load time (LCP), responsiveness (INP), layout shift (CLS) |
console.time() |
duration of a specific calculation |
Always measure a production build (npm run build && npm run preview) — development mode adds extra checks and is noticeably slower.
Step 2: Understand why components re-render
A component re-renders when its state changes, its parent re-renders, or a context it reads changes. Re-rendering is not a problem in itself — it only matters when it's expensive or happens very often. This demo counts renders so you can see the effect of state placement:
import { useRef, useState } from 'react';
function RenderCount({ label }) {
const count = useRef(0);
count.current += 1;
return <small style={{ color: 'gray' }}> {label} rendered {count.current}×</small>;
}
function Sidebar() {
return <aside style={{ background: '#f6f8fa', padding: 6 }}>Sidebar<RenderCount label="Sidebar" /></aside>;
}
// ❌ State at the top: every keystroke re-renders Sidebar too
function SlowPage() {
const [text, setText] = useState('');
return (
<div style={{ border: '1px solid #ddd', padding: 8, marginBottom: 8 }}>
<strong>State at top</strong><RenderCount label="Page" />
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="type here" style={{ display: 'block' }} />
<Sidebar />
</div>
);
}
// ✅ State moved down into the component that needs it
function SearchBox() {
const [text, setText] = useState('');
return <input value={text} onChange={(e) => setText(e.target.value)} placeholder="type here" style={{ display: 'block' }} />;
}
function FastPage() {
return (
<div style={{ border: '1px solid #ddd', padding: 8 }}>
<strong>State moved down</strong><RenderCount label="Page" />
<SearchBox />
<Sidebar />
</div>
);
}
export default function App() {
return (
<div style={{ width: 360 }}>
<SlowPage />
<FastPage />
</div>
);
}Note: The render counters write to a ref during render purely for demonstration. Don't do this in real components.
Step 3: Avoid unnecessary work
| Technique | What it fixes | Lesson |
|---|---|---|
Move state down / pass children |
parents re-rendering big subtrees | Composition |
memo |
expensive child re-rendering with same props | memo |
useMemo |
expensive calculation repeated every render | useMemo |
useCallback |
new function props breaking memo |
useCallback |
Stable keys |
lists remounting instead of updating | Lists & Keys |
| Split contexts | one context change re-rendering everything | useContext |
| React Compiler | applies memoization automatically at build time | — |
Step 4: Render less at once
Rendering 10,000 rows takes time no matter how well each row is written. Virtualization renders only what's visible in the scroll area. Libraries like @tanstack/react-virtual or react-window do this for you; here's the core idea in a few lines:
import { useState } from 'react';
const ITEMS = Array.from({ length: 10000 }, (_, i) => `Row #${i + 1} — some content`);
const ROW_HEIGHT = 28;
const VIEW_HEIGHT = 200;
export default function App() {
const [scrollTop, setScrollTop] = useState(0);
const first = Math.floor(scrollTop / ROW_HEIGHT);
const visibleCount = Math.ceil(VIEW_HEIGHT / ROW_HEIGHT) + 1;
const visible = ITEMS.slice(first, first + visibleCount);
return (
<div>
<div
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
style={{ height: VIEW_HEIGHT, overflowY: 'auto', border: '1px solid #ccc', width: 300, position: 'relative' }}
>
<div style={{ height: ITEMS.length * ROW_HEIGHT }}>
{visible.map((text, i) => (
<div
key={first + i}
style={{ position: 'absolute', top: (first + i) * ROW_HEIGHT, height: ROW_HEIGHT, left: 0, right: 0, padding: '4px 8px', boxSizing: 'border-box', borderBottom: '1px solid #eee' }}
>
{text}
</div>
))}
</div>
</div>
<p>{ITEMS.length.toLocaleString('en-US')} rows, but only {visible.length} DOM nodes rendered.</p>
</div>
);
}Other ways to render less: pagination, "load more" buttons, and transitions (useTransition, useDeferredValue) to keep typing responsive while big updates happen in the background.
Step 5: Ship less JavaScript
Load time often matters more than render speed:
- Code splitting:
lazy(() => import('./AdminPanel.jsx'))loads rarely used screens on demand. - Check your dependencies: a date or charting library can add hundreds of kilobytes. Use
npx vite-bundle-visualizerto see what's in your bundle. - Server rendering / Server Components: send HTML first and keep server-only code out of the bundle.
- Optimize images: correct sizes, modern formats (WebP/AVIF),
loading="lazy"for off-screen images.
Debouncing expensive reactions
Expensive work triggered by fast events (typing, scrolling, resizing) can be debounced so it runs only after the user pauses:
import { useEffect, useState } from 'react';
let searches = 0;
export default function App() {
const [text, setText] = useState('');
const [debounced, setDebounced] = useState('');
const [log, setLog] = useState([]);
useEffect(() => {
const id = setTimeout(() => setDebounced(text), 400);
return () => clearTimeout(id);
}, [text]);
useEffect(() => {
if (!debounced) return;
searches += 1;
setLog((l) => [`search #${searches}: "${debounced}"`, ...l].slice(0, 5));
}, [debounced]);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="Type a long word quickly" />
<p>Keystrokes cause re-renders, but searches run only after a 400 ms pause:</p>
<ul>{log.map((l) => <li key={l}>{l}</li>)}</ul>
</div>
);
}A performance checklist
- Measure with the Profiler in a production build.
- Find components that render often and take long.
- Restructure first: move state down, pass
children, split components. - Then memoize the expensive parts (
memo,useMemo,useCallback) — or enable the React Compiler. - Virtualize long lists; use transitions for heavy updates.
- Split code and trim dependencies to load faster.
- Measure again to confirm the improvement.
Tip: Premature optimization makes code harder to read for no benefit. A clean component structure solves most performance problems before they appear.
Test yourself
What should you do before optimizing a slow React screen?
- Wrap every component in memo
- Measure with the React Profiler in a production build
- Rewrite it with class components
- Remove all state
What does list virtualization do?
- Caches API responses
- Renders only the rows visible in the scroll area
- Moves rendering to a server
- Sorts lists faster
Typing in an input re-renders a large sidebar in the same parent. What is the simplest fix?
- Use a class component
- Move the input's state down into a small component
- Add more keys
- Use dangerouslySetInnerHTML