Wednesday, May 13, 2020

React.Profiler component example

In the previous post we saw in detail about the React.Profile component and how it is used to capture performance metrics of a React Component. In this post we shall see a small example on how to use the React.Profile component to measure and display performance metrics.

We will use the useEffect example and add React.Profile to it. The sample consists of a Parent component App, child component UseEffectComponent and the Root ReactDOM to load the App component. We will add Profiler to the App component in the Root and add Profiler component for UseEffectComponent in the parent App component as follows. Remember we are using create-react-app boilerplate to create these examples which will have additional supporting files.

index.js (adds Profiler to the App component)

import React, {Profiler} from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
<Profiler id="RootProfiler" onRender={onRender}>
    <App />
</Profiler>,
document.getElementById('root'));

function onRender(id,phase,actualDuration)
{
  console.log(`${id} - ${phase}: ${actualDuration}`)
}

serviceWorker.unregister();


App.js (adds profiler to the child component UseEffectComponent)

import React, {Profiler} from 'react';
import UseEffectComponent from './UseState';

class App extends React.Component {
  render() {
    function onRender(id,phase,actualDuration)
    {
      console.log(`${id} - ${phase}: ${actualDuration}`)
    };

    return (
      <div className="App">
        <header className="App-header">
          <Profiler id="ChildProfiler" onRender={onRender}>
            <UseEffectComponent/>
          </Profiler>          
        </header>
      </div>
    );
  };
}

export default App;

Build and run the application, we will see the following metrics displayed in the console when the Application loads. These metrics are for the initial mount of the Components.




Now trigger a re-render action by triggering any event in the components, in this case we will click the button to trigger re-render, once triggered notice that the update performance metrics are reflected in the console for the re-render action.




Search Flipkart Products:
Flipkart.com

No comments: