let’s say we have an array of ids [100, 101, 102] as the current state and we use this ids as key attributes when constructing a list of li
item. If we add a new id into the array as [100, 101, 102, 103], then of course React can know that it only need to constuct a new item corresponding to 103 therefore minimize DOM manipulation.
But what if click a button to reverse the array, so it is [102, 101, 100], since the position change, even though we do supply keys, can React be smart enough to know that it doesn’t need to construct 3 new li items, just need to re-order 3 exsiting ones?
4
Answers
Yes, React is made to refresh the DOM quickly and to improve re-renders. When you invert the array in the scenario you described, React can intelligently identify that the overarching items haven’t changed, but the essential characteristics have. As a result, React will rearrange the current
<li>
items rather than creating new ones.The virtual DOM representations of the past and present are compared by React using a reconciliation method called "diffing" to find the bare minimum of changes needed to update the actual DOM. React can keep track of an element’s identity across renderings thanks to the keys supplied to it. React utilises a diffing method when it comes across a list of keys, trying to match and reorder the items based on their keys rather than rebuilding them.
Reordering items would effect sure, and rendering would be slow than when its int the first order state.
read this from documentation:
Anyway, avoid using indexes when rendering lists, use instead a unique string to do so, because indexes could causes unwanted issues.
Yes, react is smart enough to know that it does not need to re create three new items, it will just update the correct elements.
You can see it here in the sandbox I forked from the react docs. In this example, two counters are rendered with two unique stable keys. You can try updating the both counters, and then hit the switch order button, react will switch the counters and maintain the counts correctly, because it is not recreating the counters but updating them based on there positions in UI tree, which remain the same due to the stable key provided.
When you add or reverse the list of items, the entire
<ol>
or<ul>
will be re-rendered in full.Even if you memoize the list, it will still render every item within it, since you will be calling
Array.prototype.map
on the entire list each time you render it.