The Profiler
component in React is a powerful tool for measuring rendering performance programmatically, allowing developers to identify areas of their application that need optimization.
Profiler
component wraps around a React tree and measures its rendering performance by providing an onRender
callback with detailed information about what was rendered and how much time it took.id
prop is used to identify the part of the UI being measured, while the onRender
callback is called every time components within the profiled tree update.Profiler
component, wrap it around a React tree by passing an id
and an onRender
callback as props.onRender
callback receives information about what was rendered, including:id
prop of the <Profiler>
tree that has just committed."mount"
) or re-rendered ("update"
or "nested-update"
).<Profiler>
and its descendants for the current update.<Profiler>
subtree without optimizations.import { Profiler } from 'react';
function onRenderCallback(
id, // the "id" prop of the Profiler tree
phase, // "mount" or "update"
actualDuration, // time spent rendering
baseDuration, // estimated total time without memoization
startTime, // when React started rendering
commitTime, // when React committed the update
) {
console.log({ id, phase, actualDuration, baseDuration,
startTime, commitTime });
}
function App() {
return (
<div>
<Profiler id="Sidebar" onRender={onRenderCallback}>
<Sidebar />
</Profiler>
<PageContent />
</div>
);
}
In this example, the Profiler
wraps around the Sidebar
component to measure its rendering performance. The onRender
callback logs render timings and performance details that can be used to identify and fix bottlenecks.
The Profiler
component in React is an essential tool for measuring rendering performance programmatically. By analyzing its output, developers can pinpoint inefficient components and optimize them to enhance the user experience.