React: Parent component re-renders all children, even those that haven’t changed on state change

If a parent component is updated, does React always update all the direct children within that component?

No. React will only re-render a component if shouldComponentUpdate() returns true. By default, that method always returns true to avoid any subtle bugs for newcomers (and as William B pointed out, the DOM won’t actually update unless something changed, lowering the impact).

To prevent your sub-component from re-rendering unnecessarily, you need to implement the shouldComponentUpdate method in such a way that it only returns true when the data has actually changed. If this.props.messages is always the same array, it could be as simple as this:

shouldComponentUpdate(nextProps) {
    return (this.props.messages !== nextProps.messages);
}

You may also want to do some sort of deep comparison or comparison of the message IDs or something, it depends on your requirements.

EDIT: After a few years many people are using functional components. If that’s the case for you then you’ll want to check out React.memo. By default functional components will re-render every time just like the default behavior of class components. To modify that behavior you can use React.memo() and optionally provide an areEqual() function.

Leave a Comment