Skip to content

Instantly share code, notes, and snippets.

@carlows
Created September 19, 2016 21:35
Show Gist options
  • Save carlows/f7d8e6161ee94154a5a3d38efa9f2055 to your computer and use it in GitHub Desktop.
Save carlows/f7d8e6161ee94154a5a3d38efa9f2055 to your computer and use it in GitHub Desktop.

Author

Carlos Martinez

Context

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.

Solution

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment