Handle dynamically growing list in react js

Viewed 778

I have a component for displaying a list, and this component is rendered from a parent component. I am currently generating the contents of this list using a for loop. Like -

let content = []
for (let i = 0; i < list.length; i++) {
  content.push(
    <div>
      <p> list[i].something </p>
      <p> list[i].somethingElse </p>
    </div>
  )
}

return content;

Now whenever a new object is added to this list, all the previous objects of the list, and the newly added object get rendered. This becomes extremely slow when the list contains around 1000 objects.

Is there a way by which only the new added can be added and rendered, without re-rendering all the previous entries of the list again?

2 Answers

This must be mainly because you havent added key, try the following code after setting an id for each list item and assign it to key prop.

let content = []
for (let i = 0; i < list.length; i++) {
  content.push(
    <div key={list[i].id}>
      <p> list[i].something </p>
      <p> list[i].somethingElse </p>
    </div>
  )
}

return content;

If the list is a static one which doesnt change, index can also be used as the value for key prop.

let content = []
for (let i = 0; i < list.length; i++) {
  content.push(
    <div key={i}>
      <p> list[i].something </p>
      <p> list[i].somethingElse </p>
    </div>
  )
}

return content;

You shoulda unique id for each item to render list item component. You can do on the ES6 something like:

const renderList = (list) => (
 list.map(item =>
  <div key={item.id}>
   <p>{item.something}</p>
   <p>{item.somethingElse}</p>
  </div>
);
Related