Ali Taee
Ali Taee

Reputation: 198

How to handle the render of a large list of items in react?

I have a large list of items to render and list data get updated in realtime with socket-io. How to handle performance issues? it gets updated heavily and table of items rendered so many times.

Upvotes: 4

Views: 4049

Answers (2)

eriegz
eriegz

Reputation: 385

I was in the same boat and solved my problem a different way, by implementing the shouldComponentUpdate lifecycle method in my component:

shouldComponentUpdate(nextProps) {
  // Note: lodash's "isEqual" method is useful for performing a deep comparison
  // of the given objects, which is more than JavaScript can do natively:
  return !_.isEqual(this.props.listItems, nextProps.listItems);
}

This is perhaps a better overall solution, because:

  • it's easier to implement (i.e.: don't have to wrap your existing component in a React.memo() HOC
  • it's supported even on older versions of React that don't have "memo" (i.e.: versions older than 16.6.0, which was released in 2018)

Upvotes: 0

thedude
thedude

Reputation: 9812

There are a couple of things to consider:

  1. render cost of a large list
  2. updating an item

For #1 you can try using a windowing library such as react-virtualized, this will make the burden on the DOM much lighter, instead of rendering thousands of items, you will actually be rendering only a few tens.

For #2 make sure that when an item updates, only that items updates and not the list. You can use memo to ensure your list items are only renders again when their props change.

Upvotes: 3

Related Questions