I'm a newbie in React, and I'm trying to find out how to improve rendering performance.
Considering the Todos with Undo example, all todos are being re-rendered anytime I create a new Todo:
How can I optimize to render only new items?
I'm a newbie in React, and I'm trying to find out how to improve rendering performance.
Considering the Todos with Undo example, all todos are being re-rendered anytime I create a new Todo:
How can I optimize to render only new items?
To be precise each component should not be being re-rendered - as in the browser DOM being updated and the browser re-rendering the HTML elements. There is an important distinction in React between the virtual DOM (see React introductory materials) being updated and actual DOM elements being updated.
After an update cycle (i.e. calls to render()), before updating the actual DOM, React performs a diff (conceptually) between your current virtual DOM, and the new virtual DOM and only updates the browser DOM elements which have changed since your last update (to within reason). This should allow the browser to only update and re-render the elements that actually need updating / re-rendering.
This is essence of React, rather than toggling different HTML element attributes .etc. based on state updates and the complexity that leads to, you declare how your component should be rendered based on its props+state and React takes care of the details. Aka. declarative vs imperative programming.
This method is not perfect though, for complex applications/components regenerating the virtual DOM can be a sufficiently complex operation that it is worth optimising. In this case you can override the componentShouldUpdate() method on your components.
In the componentShouldUpdate() method you should compare the current props and state of your component to the new (post-update) props/state of the component to determine if the props/state of the component should be updated, and the component re-render.
If the props+state are the same and do not need updating then return false. Used appropriately on components high up in the hierarchy (i.e. with lots of children) this can be a performance boon.
I wouldn't recommend worrying about it unless you actually find you have performance issues though.
On a side note if your are just performing a shallow comparison (i.e. newProps !== oldProps || newState !== oldState) rather than a deep comparison, you can use PureComponent instead of Component. PureComponent includes a default implementation of shouldComponentUpdate which performs precisely this comparison.