Carlos Martinez
React renders all children components whenever the parent component updates its state, e.g:
class Parent {
constructor() {
this.state = { text: 'bar' };
}
componentDidMount() {
this.setState({ text: 'foo' });
}
render() {
console.log('rendered parent');
return (<Child text={this.state.text} />);
}
}
class Child {
render() {
console.log('rendered child');
return (
<div>{this.props.text}</div>
);
}
}
In this situation, whenever we call setState
on the Parent component, the child render function will get executed when the parent render function gets executed.
When we have a big list of items to render, whenever we modify an item on that list, React will render all the children components in that list, which will cause performance issues if these components get complex.
We can have react to skip the update ovewritting shouldComponentUpdate
, and only returning true if the props or the state changed:
shouldComponentUpdate(nextProps, nextState) {
return !_.isEqual(this.props, nextProps) ||
!_.isEqual(this.state, nextState);
}
Note though, the implementation of this method should be fast, and we are using a deep comparison here to check if the next props are equal to the current, so we should consider using Inmutable if the data gets too complex.
Implementing this in our TimeEntryGroup
and TimeEntry
components will improve the speed of the app, because whenever we update our TimeEntries
list, we will only re render the ones that changed.