Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle dynamically growing list in react js

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?

like image 945
anuyog Avatar asked Aug 03 '26 11:08

anuyog


1 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;
like image 109
Rohith Murali Avatar answered Aug 06 '26 09:08

Rohith Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!