Why did you update?

There are different things we can do to find out which components do not need to be updated. One of the easiest is to install a third-party library that can provide the information automatically.

First of all, we have to type the following command in the terminal:

  npm install --save-dev why-did-you-update

And add the following snippet after the import statement of React in your App.js:

  import React from 'react';

if (process.env.NODE_ENV !== 'production') {
const { whyDidYouUpdate } = require('why-did-you-update');
whyDidYouUpdate(React);
}

We are basically saying that, in development mode, we want to load the library and patch React using the whyDidYouUpdate method. It is important to say that this library should not be enabled in production.

If we now go back to the List example of the previous section and we change it a little bit, we can see the library in action.

The first thing we have to do is to modify the render method as follows:

  render() { 
return (
<div>
<ul>
{this.state.items.map(item => (
<Item key={item} item={item} />
))}
</ul>

<button onClick={this.handleClick}>+</button>
</div>
);
}

Instead of rendering the single list items inside the map function, we return a custom Item component to which we pass the current item and we use the key to tell React which components existed before the update.

We can now implement the item component, extending React.Component:

  class Item extends Component

At the moment, it only implements the render method, which does what we were doing inside the render method of List:

  render() { 
return (
<li>{this.props.item}</li>
);
}

In the browser console, you can see the output from the whyDidYouUpdate function, which tells us that we can avoid re-rendering some components:

  Item.props
Value did not change. Avoidable re-render!
before Object {item: "foo"}
after Object {item: "foo"}

Item.props
Value did not change. Avoidable re-render!
before Object {item: "bar"}
after Object {item: "bar"}

In fact, even if React does not touch the DOM for the foo and bar items, their render methods are still being called with the same props, which makes React perform an additional job. This is very useful information that is sometimes not easy to find.

Now, we can easily fix the issue by modifying the extends statement of the Item component from extends and React.Component to:

  class Item extends PureComponent

If we now open the browser and run the application again, clicking the + button, we see that nothing is logged into the console, which means that we are not rendering any Item for which the props are not changed.

Regarding perceived performance, there is not much difference in this small example, but if you imagine a big application that shows hundreds of list items, this small change can represent a huge win.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset