Immutability

As we have seen, the most powerful tool we can use to improve the performance of our React application is shouldComponentUpdate using PureComponent.

The only problem is that PureComponent uses a shallow comparison method against the props and state, which means that if we pass an object as a prop and we mutate one of its values, we do not get the expected behavior.

In fact, a shallow comparison cannot find mutation on the properties and the components never get re-rendered, except when the object itself changes.

One way to solve this issue is using immutable data: Data that, once it gets created, cannot be mutated.

For example, we can set the state in the following mode:

  const obj = this.state.obj;

obj.foo = 'bar';

this.setState({ obj });

Even if the value of the foo attribute of the object is changed, the reference to the object is still the same and the shallow comparison does not recognize it.

What we can do instead is create a new instance every time we mutate the object, as follows:

  const obj = Object.assign({}, this.state.obj, { foo: 'bar' });

this.setState({ obj });

In this case, we get a new object with the foo property set to bar , and the shallow comparison would be able to find the difference.

With ES6 and Babelthere is another way to express the same concept in a more elegant way, and it is by using the object spread operator:

  const obj = { 
...this.state.obj,
foo: 'bar'
};

this.setState({ obj });

This structure is more concise than the previous one, and it produces the same result; but, at the time of writing, it requires the code to be transpiled to be executed inside the browser.

React provides some immutability helpers to make it easy to work with immutable objects, and there is also a popular library called immutable.js , which has more powerful features but it requires you to learn new APIs.

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

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