How to profile React app performance with the Profiler API
· Category: React
Short answer
The React Profiler measures how often a component renders and the time each render takes. It helps identify performance bottlenecks in your component tree.
Steps
- Import
Profilerfromreact. - Wrap a section of your app in
<Profiler id="Name" onRender={callback}>. - In the callback, log
actualDuration,baseDuration, andphase.
Example
import { Profiler } from 'react';
function onRender(id, phase, actualDuration) {
console.log(id, phase, actualDuration);
}
function App() {
return (
<Profiler id="App" onRender={onRender}>
<Dashboard />
</Profiler>
);
}
Tips
- Use the Profiler in production builds sparingly; it adds overhead.
- Combine with
React.memoanduseMemoto address slow renders identified by profiling. - React DevTools provides a visual profiler that is easier to use for most cases.