Sub topic 2
Reading React Profiler Results
Assume you know JavaScript functions and arrays, React components, props, state, hooks, and basic browser developer tools.
Reading the flamegraph and ranked charts
In React DevTools Profiler, record a user action such as typing or opening a panel. The flamegraph shows the component tree for a commit. Wider bars generally represent more rendering time in that subtree. Select a component to inspect its render duration and props.
The ranked chart orders components by render time. Start with the largest costs, but check whether the component rendered because of a real data change or because an avoidable parent update reached it.
Finding out why a component rendered
In the Profiler, enable settings that record why components rendered when available. A component may have rendered because:
- Its state changed.
- Its parent rendered.
- A prop changed.
- A context value changed.
- A hook value changed.
Compare the changed values. A new object or function can count as a prop change even when its contents are equal.
> callout note > A render is not automatically a problem. Optimize when profiling shows that the render contributes to a slow interaction or visible delay.
Common causes of unnecessary re-renders
Common causes include putting state too high in the tree, creating object and function props during every render, changing context values frequently, and recalculating expensive data unnecessarily. Large lists also make ordinary renders more expensive.
Fixing renders by moving state down
State colocation means keeping state near the component that uses it. This prevents unrelated siblings from rendering when the state changes.
Memoizing selected work
React.memo skips a child render when its props are shallowly equal. useMemo caches a calculated value. useCallback caches a function identity. Use them when measurement shows a benefit.
import { memo, useCallback, useMemo, useState } from "react";
function SearchBox() {
const [query, setQuery] = useState("");
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
export function Page({ items }) {
const [selectedId, setSelectedId] = useState(null);
const sorted = useMemo(
() => [...items].sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
const select = useCallback((id) => setSelectedId(id), []);
return (
<>
<SearchBox />
<p>Selected: {selectedId}</p>
<ul>{sorted.map((item) => <Row key={item.id} item={item} onSelect={select} />)}</ul>
</>
);
}Exercise
Why might React.memo fail to skip a Row render?
Show answer
A prop may have a new object or function identity, even when its contents appear unchanged.