Tracking down re-renders using unique object identifiers in React.

March 14, 2017 Tips JavaScript React

I’ve been using this bit of code a bunch recently to help track down unnecessary re-renders in a React component.

(function() {
  if (typeof Object.id == "undefined") {
    let id = 0;
    Object.id = function(o) {
      if (typeof o.__uniqueid == "undefined") {
        Object.defineProperty(o, "__uniqueid", {
          value: ++id,
          enumerable: false,
          writable: false
        });
      }
      return o.__uniqueid;
    };
  }
})()

(source)

If you’re using PureRenderMixin or a custom shouldComponentUpdate method changes to objects stored in state could cause a re-render. Using this you can log and keep track of these changes. For example I put this in the componentWillReceiveProps method:

console.log(Object.id(this.state.data));

And this is the output:

As you can see the ID gets incremented each time a new object is created making it clear that a change was made. This has helped me multiple times so I wanted to share!



Powered by Gatsby and WordPress.