Enhanced React Profiler
Explain how to use the improved Profiler API to measure the rendering performance of components.
import React, { Profiler } from 'react';
function onRenderCallback(
id, // the 'id' prop of the Profiler tree that has just committed
phase, // either 'mount' (if the tree just mounted) or 'update' (if it re-rendered)
actualDuration, // time spent rendering the committed update
baseDuration, // estimated time to render the entire subtree without memoization
startTime, // when React began rendering this update
commitTime, // when React committed this update
interactions // the Set of interactions belonging to this update
) {
// Aggregate or log render timings...
console.log(
`id: ${id}, phase: ${phase}, actualDuration: ${actualDuration}, baseDuration: ${baseDuration}, start: ${startTime}, commit: ${commitTime}`
);
}
function MyComponent() {
// ... component implementation ...
}
function App() {
return (
<Profiler id="MyComponentProfiler" onRender={onRenderCallback}>
<MyComponent />
</Profiler>
);
}
export default App;
This code snippet shows how to use the Profiler component in React to gather performance measurements from React's rendering lifecycle. A callback function 'onRenderCallback' is defined to handle the measurements which include timestamps and duration of the render phases. The Profiler is then used to wrap the target component, 'MyComponent', and the 'id' and 'onRender' props of the Profiler are set to associate it with the callback function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced React Profiler Example</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="./App.js"></script>
</body>
</html>
This is the HTML file that includes the root element where our React application will be rendered. The React and ReactDOM libraries are included via CDN, and 'App.js' is the JavaScript file that includes our React application code, including the Profiler example.
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#root {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
This CSS code styles the HTML body and root div. It resets the margin, sets a default system font stack, enables font smoothing, and centers the content (#root) both horizontally and vertically within the viewport.