Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  • github: https://github.com/chancesmith/reactjs-optimize-list-updates/tree/master/src
  • codesandbox: https://codesandbox.io/s/wn45qw44z5

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?

like image 357
Chance Smith Avatar asked Nov 15 '18 20:11

Chance Smith


Video Answer


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

like image 139
Eran Avatar answered Nov 15 '22 05:11

Eran