Sub topic 2
Measure first with the Profiler
This chapter assumes you know function components, JSX, useState and useEffect, and how props and children flow between components. It also assumes you know that JavaScript objects, arrays and functions are reference values. You will learn how to find out whether a render is a real problem before you change any code.
Why measure before optimizing
A re-render is not a bug. React renders components often, and most renders take well under a millisecond. Adding memo, useMemo or useCallback to code that is already fast makes it longer, harder to read, and slightly slower, because React must store and compare the cached values.
Measuring answers three questions:
- Is the interface actually slow, or does it only feel like it should be?
- Which components are expensive to render?
- Why did a given component render at all?
Without answers to these, you tend to memoize the wrong component. The cost sits somewhere else, and the code gets worse for no gain.
Setting up the Profiler
React DevTools is a browser extension for Chrome, Firefox and Edge. After you install it, two tabs appear in the browser developer tools: Components and Profiler.
Use a development build to see why components rendered, but remember that development builds are slower. React adds extra checks, and in Strict Mode it renders components twice to expose impure code. Absolute times from a development build are inflated. Use them to compare components with each other, and confirm the final result in a production build.
To get a production build with profiling enabled, build with your tool's profiling option (for example, a profiling build in your bundler), because a plain production build strips the data the Profiler needs.
Recording a session
- Open the Profiler tab.
- Click the gear icon and enable Record why each component rendered while profiling.
- Click the record button.
- Perform the exact interaction you suspect is slow, such as typing in a search box.
- Click the record button again to stop.
Keep the recording short and focused on one interaction. A long recording mixes many unrelated renders and makes the result hard to read.
Reading the results
Commits
React works in two phases. In the render phase it calls your components to work out what the screen should look like. In the commit phase it applies the changes to the DOM. Each time React commits, the Profiler records one commit. The bar chart at the top shows one bar per commit. Taller and more yellow bars took longer. Blue and gray bars were cheap.
Click a bar to inspect that commit. If one keystroke produces one commit, that is normal. Many commits for one action can point to effects that set state in a chain.
Flame graph
The flame graph shows the component tree for the selected commit. Each bar is a component. Its width shows how long that component and its children took to render. Its color shows relative cost:
- Gray: the component did not render in this commit.
- Blue to yellow: the component rendered, and warmer colors mean more time.
Gray bars are the point of memo. If you apply memo correctly, a component that used to be colored becomes gray when its props do not change.
Ranked chart
The ranked view sorts components in the commit by their own render time, longest first. Use it to find the single most expensive component. Start with the top entries and ignore the long tail of tiny ones.
Why did this render?
With the "record why" option on, hover over or select a component in the flame graph. The side panel lists the reason. The common reasons are:
| Reason shown | Meaning | Typical response |
|---|---|---|
| Props changed: `options` | A prop has a new value or reference | Check whether the prop is a new object or function each render |
| State changed | The component's own `useState` or `useReducer` changed | Expected. Consider whether the state lives too high in the tree |
| Hooks changed | A hook inside the component changed, such as a context value | Inspect the hook that changed |
| The parent component rendered | No prop changed, but the parent re-rendered | A candidate for `memo` or for moving state down |
The last reason is the most useful for this tutorial. When a component renders only because its parent rendered, and its output did not change, the render was wasted work.
A worked example
This component has a list that is slow to render and a text field that is cheap. The state for the text field lives in the parent.
import { useState } from 'react';
function SlowItem({ text }) {
const start = performance.now();
while (performance.now() - start < 2) {
// Simulate 2 ms of expensive work per item.
}
return <li>{text}</li>;
}
const items = Array.from({ length: 100 }, (_, i) => `Item ${i}`);
export function Page() {
const [draft, setDraft] = useState('');
return (
<>
<input value={draft} onChange={(e) => setDraft(e.target.value)} />
<ul>
{items.map((text) => (
<SlowItem key={text} text={text} />
))}
</ul>
</>
);
}Record while typing a few characters. Expect the following in the Profiler:
- Each keystroke produces one commit of roughly 200 ms, since 100 items take about 2 ms each.
- The flame graph shows
Pageand everySlowItemcolored. - The reason for each
SlowItemis "The parent component rendered". Itstextprop is the same string every time.
The input feels laggy, and the Profiler shows exactly why: typing re-renders 100 components whose output never changes. Now you have a measured problem and a measured cause. Fixes are covered in later chapters, such as wrapping SlowItem in memo or moving the draft state into its own component. After applying one fix, record the same interaction again. The SlowItem bars should turn gray and the commit time should fall to a few milliseconds.
Measuring in code with the Profiler component
DevTools is not always available, for example when you want to log timings in a test or a staging environment. React provides a Profiler component that reports timings for the subtree it wraps.
import { Profiler } from 'react';
function onRender(id, phase, actualDuration, baseDuration) {
console.log(
`${id} ${phase}: actual ${actualDuration.toFixed(1)} ms, base ${baseDuration.toFixed(1)} ms`
);
}
export function App() {
return (
<Profiler id="list" onRender={onRender}>
<Page />
</Profiler>
);
}The callback receives these values:
id: the string you gave theProfiler.phase:"mount"for the first render,"update"for later ones (React also reports"nested-update").actualDuration: time spent rendering the subtree in this commit. This shows how well memoization is working, because skipped components cost nothing.baseDuration: an estimate of the time to render the whole subtree with no memoization. Compare it toactualDurationto see how much memoization saves.
The Profiler component adds overhead, and in React's production builds it is disabled unless you use the profiling build. Treat it as a measurement aid, not as permanent instrumentation.
Pitfalls when measuring
- Measuring in development only. Strict Mode double-renders and extra warnings inflate times. A component that looks slow in development may be fine in production.
- Counting renders instead of cost. A component that renders 50 times in 0.05 ms each is not a problem. A component that renders once for 300 ms is. Look at duration, not render count.
- Using
console.logrender counts as the only evidence. Theconsole.log('render row')lines from earlier chapters show that a render happened, not what it cost. - Fast machine, slow users. Your laptop is probably quicker than your users' devices. Use the browser's CPU throttling (for example 4x or 6x slowdown) to approximate a mid-range phone.
- Changing several things at once. If you apply three fixes and record once, you cannot tell which one helped. Change one thing, record, compare.
- Confusing render cost with other cost. If the Profiler shows small render times but the page still feels slow, the cause is probably outside React rendering, such as layout, large images, or heavy work in an event handler.
A decision rule
Use this rule when you look at a recording:
- If the whole commit is only a few milliseconds, stop. There is no problem to solve.
- If the commit is slow and one component dominates the ranked chart, look at that component first. Maybe its own work is expensive and
useMemocan help, or maybe it should render less often. - If the commit is slow because many components render for the reason "The parent component rendered", the fix is in how often the parent re-renders or how its children receive props.
- If a component renders because a prop changed but the value looks identical, check for a new object, array or function created on each render.
Steps 3 and 4 lead directly to the next chapters on referential equality and React.memo.
Exercise
In the Profiler you record one keystroke in a form. The commit takes 180 ms. The ranked chart shows 60 ProductCard components at about 3 ms each. Each one lists "The parent component rendered" as its reason, and their props did not change. What does this tell you, and what should you do next?
Show answer
The cost comes from many cheap-looking components re-rendering needlessly. Each is only 3 ms, but 60 of them add up to about 180 ms. The Profiler shows the renders are wasted, since no props changed. Fix one thing, for example by wrapping ProductCard in memo or moving the form state into a smaller component, then record the same keystroke again. Check that the cards turn gray and the commit time drops.
Exercise
A teammate wants to add useMemo everywhere because a component logged "render" 40 times during a short session. What measurement would you ask for first, and why?
Show answer
Ask for a Profiler recording of the specific slow interaction, looking at commit duration and per-component render time. A render count alone does not show cost. If each render takes a fraction of a millisecond, the 40 renders are harmless and the memoization would only add code and comparison overhead.