jakeaaron jakeaaron - 24 days ago 6
React JSX Question

ReactJS - Performance implication of `setState` in parent component

I am building a large application using React where a shared parent component handles all the state for multiple children. Some of these children render lists of over 1000 items.

I realize that toggling a boolean inside the parent with

setState
will re-render the parent, in turn rendering all of its children again.

My question is, if none of the list items to the child changes, then does the re-render cause the child to loop through and build the gargantuan list all over again-–every time the parent re-renders?

Where does the virtual DOM play a role in this? Does the child re-build the list but the DOM never has to update because the diff sees that the list elements haven't changed?

Edit:
Finally, if that is the case, how does the
key
property affect the list re-rendering? If I have 1000 items all with unique keys, but 3 items have keys that are
null
, (meaning they have the same key value) then does the entire list re-render?

Answer

Does the child re-build the list but the DOM never has to update because the diff sees that the list elements haven't changed?

Yes exactly. You can read about this in much more detail here: https://facebook.github.io/react/docs/reconciliation.html

Typically this operation is so fast you can hardly tell, however at some point the diff patch will become slow. Flipping a boolean is probably not a big deal, but flipping that boolean at 60 fps may cause some jank.

There are usually smart things you can do to prevent any noticeable lag, but implementing shouldComponentUpdate is always a choice.

https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

While you're there, read about React.PureComponent in case this is something that interests you.