Skip to content

Exposing React Performance Tools in the Browser Console

Posted on:March 25, 2016

The React docs on Performance Tools is quite lacking as to how it should be used, so I had to do some digging around to figure out how it worked.

It turns out Perf.start() doesn’t work in component lifecycles1, raising an ugly internal error that hasn’t been properly dealt with yet (see this issue for more details).

This prevents us from doing some things like:

  1. Calling Perf and measuring performance repeatedly.

  2. Using Perf to measure between arbitrary points in deeper parts of your component hierarchy.

I solved these problems by exposing React’s performance tools in the browser. There are a few ways to do this. If you’re using webpack, you can use expose-loader, which allows us to attach modules to the global object:

$ npm install expose-loader --save-dev
module: {
  loaders: [
    { test: require.resolve("react-addons-perf"), loader: "expose?ReactPerf" },
  ];
}

You can then start measuring in the console at any time:

// in browser console
> ReactPerf.start()

and you can call Perf.stop() in a component lifecycle method:

import Perf from 'react-addons-perf'
 
class SomeComponent extends React.Component {
 
  componentDidUpdate() {
    Perf.stop()
    Perf.printWasted()
  }
 
  render() { ... }
}

or in the browser console:

// in browser console
> ReactPerf.stop()
> ReactPerf.printWasted()

Footnotes

  1. perf.stop() and the rest of the printing methods do.