Prevent Component/PureComponent with styled-components from re-rendering all items after state change

Viewed 1429

After adding styled-components to this example, we've noticed that our list component updates everything when only one item in state is modified.

The list rendering highlights (from React dev-tools) are excessive when adding/removing a single entry. One item is removed/added, then all items get highlighted.

enter image description here

code samples

Here is an example of the right list component (CategorizedList.js)

import styled from "styled-components";

const Item = styled.li`
  color: #444;
`;

class CategorizedList extends PureComponent {
  render() {
    return (
      <div>
        {this.props.categories.map(category => (
          <ul>
            <li key={this.props.catStrings[category]}>
              {this.props.catStrings[category]}
            </li>
            <ul>
              {this.props.items.map((item, index) =>
                item.category === category ? (
                  <div key={item.label + index}>
                    <Item>{item.label}</Item>
                  </div>
                ) : null
              )}
            </ul>
          </ul>
        ))}
      </div>
    );
  }
}

Preference

I'd prefer to use PureComponent so that shouldComponentUpdate() gets handled automatically.

Question

How can we make sure only the modified objects in items state are re-rendered?

1 Answers

If the data changes , the view will re-render. It shouldn't be an expensive process since it happens once on add/remove action. If you find performance issues it might be caused from something else.

In general this would be the way you can have some control on pure-components re-render: https://reactjs.org/docs/react-api.html#reactmemo

Related