Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 132 ยท Performance

Profiling and Debugging Performance

Measure before you optimize. Use the React DevTools Profiler, the Profiler component, render counters and prop diffing to find wasted renders, plus performance budgets and web vitals.

Performance advice is full of folklore: "wrap everything in memo", "inline functions are slow", "avoid re-renders". Most of it solves problems you do not have. The professional approach is the opposite: measure first, find the actual bottleneck, change one thing, measure again. A render that takes 0.2 ms and happens ten times is not your problem. A render that takes 80 ms on every keystroke is.

This lesson gives you the tools to see what React is doing. Some are tools you install (React DevTools), some are built into React (the <Profiler> component), and some are tiny helpers you can write in ten lines, which we run live here. It completes the performance chapter that started with Rendering in Depth, memo and virtualization.

What to measure

"The app feels slow" can mean four different things, with four different fixes:

Symptom Likely cause Where to look
Slow first load Big JavaScript bundle, slow network, slow server Bundle analyzer, network tab, code splitting
Typing or clicking lags Expensive render or too many components re-rendering React Profiler, render counters
Scrolling stutters Too many DOM nodes, layout thrash, heavy scroll handlers Browser Performance panel, virtualization
Page jumps while loading Layout shift (content without reserved space) Cumulative Layout Shift in web vitals

React's own cost is only one of those rows. Start with the symptom, then pick the tool.

The React DevTools Profiler (read-only)

React DevTools is a browser extension (Chrome, Edge, Firefox) that adds Components and Profiler tabs to the developer tools. It does not run inside our sandboxed editor, so what follows is a description of how to use it in your own app.

  1. Open your app and the Profiler tab. Press the record button.
  2. Do the slow thing: type in the search box, open the menu, switch a tab.
  3. Stop recording. You get a list of commits (each time React updated the screen) as bars. Taller, yellower bars took longer.
  4. Click a commit. The flame graph shows the component tree for that commit: grey components did not render, coloured ones did. Their width shows how long they took.
  5. Switch to the Ranked view to list components by render time, slowest first.
  6. Click a component and read "Why did this render?" (enable Record why each component rendered while profiling in the Profiler settings). It reports "props changed", "state changed", "hooks changed" or "parent rendered".

Things to know:

  • Profile a production build when you can. Development builds are much slower because of extra checks (and StrictMode double rendering), so the absolute numbers mislead. Use npm run build and a preview server, or React's profiling build.
  • Throttle the CPU (browser Performance panel, 4x or 6x slowdown) to approximate a mid-range phone. Your laptop hides problems your users see.
  • Look for patterns, not single numbers: "this component renders 40 times when I type one letter" is the signal.

The Profiler component

React also lets you measure from code. <Profiler id onRender> wraps a part of your tree and calls onRender every time that part of the tree commits an update.

JSX
<Profiler id="Sidebar" onRender={(id, phase, actualDuration, baseDuration, startTime, commitTime) => { /* ... */ }}>
  <Sidebar />
</Profiler>

The callback receives the profiler's id, the phase ("mount", "update" or "nested-update"), the time spent rendering the committed update (actualDuration), the estimated time to render the whole subtree without any memoization (baseDuration) and timestamps. Durations are real milliseconds, which vary from run to run, so the demos in this lesson log the parts that are deterministic: which profiler fired and how often.

The Profiler component counts commits

On mount both profilers report (mount): header committed (mount), total 1 and list committed (mount), total 1. Press "Add item": the parent re-renders, and both children re-render too since neither is memoized, so both profilers report (update) with total 2. This confirms the rule from the memo lesson in a measurable way. Be careful how you read this, though. If you wrap Header and List in memo and repeat, both profilers still report (update) with total 2: the <Profiler> elements are created by App, so they re-render with it and onRender fires even though the memoized children were skipped. A count of onRender calls tells you the profiled subtree was part of a commit, not that its components ran. For "was my component skipped?" use the durations the callback receives, or the grey (skipped) versus coloured (rendered) bars in the DevTools flame graph, or a render counter like the one below.

<Profiler> adds a little overhead and is disabled in production builds unless you use React's profiling build. Use it temporarily to investigate, or in a dedicated profiling build, not scattered through production code. Never call setState in onRender: that triggers more commits and loops.

Counting renders by hand

Often the quickest diagnostic is a render counter. Writing a ref during render is normally against the rules (Keeping Components Pure), but for temporary debugging code it is an accepted trade, as long as you delete it afterwards. This hook returns the count and logs it.

A render counter hook

Type hi (two characters) and the console reads: Parent render #1, Child render #1, then Parent render #2, Child render #2, Parent render #3, Child render #3. The child never receives different props, yet it renders on every keystroke: the exact kind of finding that tells you to move state down or memoize.

Why did this render?

A count says that something rendered. To find why, compare the props with the previous render. This helper (the idea behind the tool "why-did-you-render") logs which props changed their identity.

Finding the prop that keeps changing

Click the button once. The console shows Chart mounted and then Chart re-rendered; changed props: options, onSelect. The data prop is a module-level constant, so it is stable. options is an object literal and onSelect is an inline arrow function; both are new on every parent render, and the log names them exactly. Those are the two props to stabilize before memo can help. It is also how a real "why did this render" panel in DevTools helps you.

A re-render is not automatically a problem. Only act when a re-render is slow or frequent and visible. Many "wasted" renders cost microseconds. Optimizing them adds code complexity for no measurable gain.

Rendering is not DOM updating

Another useful measurement: how much does React change in the DOM? Rendering a component only runs your function; React then compares the result and updates only what differs. A MutationObserver shows you the real DOM changes.

Counting real DOM mutations

Click the button once. App rendered; every Row function runs again appears again (it was also logged at mount): all five Row functions ran. But the observer reports DOM mutations: 2: React changed the style attribute of the row that lost the selection and of the row that gained it, and left the other three nodes untouched. So the render cost (five function calls) and the DOM cost (two attribute writes) are different things. Most performance problems come from one or the other, and you need to know which.

Performance budgets and web vitals

A performance budget is a number you agree not to exceed, checked automatically, for example: "main JavaScript bundle under 200 KB gzipped" or "Largest Contentful Paint under 2.5 s on a mid-range phone". Without a budget, apps slow down one small feature at a time.

Google's Core Web Vitals are the standard user-centred metrics, measured in the field with real users:

Metric Measures "Good" threshold
LCP (Largest Contentful Paint) How fast the main content appears 2.5 s or less
INP (Interaction to Next Paint) How quickly the page responds to clicks and keys 200 ms or less
CLS (Cumulative Layout Shift) How much the layout jumps around 0.1 or less

React-specific advice by metric: LCP improves with smaller bundles, server rendering and code splitting. INP improves by keeping render work small, using transitions for heavy updates and virtualizing long lists. CLS improves by reserving space for images and for lazy-loaded content (see Code Splitting). Thresholds change over time, so check the current guidance.

Reporting vitals from your app uses the small web-vitals library. It needs an npm package and a real page, so this is read-only:

JavaScript
import { onCLS, onINP, onLCP } from 'web-vitals';

function sendToAnalytics(metric) {
  navigator.sendBeacon('/analytics', JSON.stringify({ name: metric.name, value: metric.value }));
}

onCLS(sendToAnalytics);
onINP(sendToAnalytics);
onLCP(sendToAnalytics);

A debugging workflow

  1. Reproduce the slowness with specific steps ("type three letters into the filter").
  2. Profile it in a production-like build with CPU throttling. Find the slowest commit and the components in it.
  3. Ask why each expensive component rendered: props changed, state changed, or only the parent.
  4. Pick the cheapest fix: move state down, pass children, remove unnecessary work, virtualize or paginate, defer with a transition. Reach for memo and useMemo after those, or let the React Compiler do it.
  5. Measure again. If the numbers did not improve, undo the change.

Also check the basics before React-level tuning: the number of DOM nodes, images without sizes, huge dependencies, an effect that fetches in a loop, and a console.log of a large object on every render (it slows the page when DevTools is open).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you profile a production build when possible?

    Development mode does extra work to help you find bugs, which slows rendering. Real numbers come from a production-like build, ideally with CPU throttling.
  2. 2. When does a <Profiler onRender> callback fire?

    The callback runs after a commit that updates the profiled part of the tree, and it receives the phase and durations. It is not a timer, and it also fires when the Profiler itself re-renders with its parent.
  3. 3. A memoized child still re-renders. Your prop-diff helper reports changed props: onSelect. What is the likely cause?

    An inline arrow function is a new object each render. Stabilize it with useCallback (or the compiler), or define it so its identity does not change.
  4. 4. In the DOM mutation demo, all five Row functions ran, but only two DOM mutations were reported. What does that show?

    Render work and DOM work are separate costs. React re-ran all Row functions but wrote only the two style attributes that changed.
  5. 5. Which Core Web Vital measures how quickly the page responds to user interactions?

    Interaction to Next Paint measures responsiveness. LCP is loading speed and CLS is visual stability.

Summary

  • Measure first: pick the symptom (load, interaction, scroll, layout shift), then the tool, then fix, then measure again.
  • React DevTools Profiler records commits, shows which components rendered and why; profile a production-like build with CPU throttling.
  • The <Profiler> component's onRender reports each committed update inside it; use it temporarily and never set state in it.
  • Small debug helpers (render counters, prop diffing) quickly find unnecessary renders and the unstable props behind them.
  • Rendering and DOM updates are separate costs; a MutationObserver shows what actually changed.
  • Set performance budgets and track Core Web Vitals (LCP, INP, CLS) with real-user data.

Next: Compound Components and Slots