sajad torkamani

React uses the key prop to uniquely identify subtrees within an array of subtrees in its virtual DOM. Being able to uniquely identify subtrees amongst siblings helps React avoid unnecessarily tearing down and rebuilding subtrees between renders.

A world without keys

Suppose you had a list that had the following trees between a render.

// First render
<ul>
  <li>Duke</li>
  <li>Villanova</li>
</ul>

// Second render
<ul>
  <li>Connecticut</li>
  <li>Duke</li>
  <li>Villanova</li>
</ul>

Without keys, React won’t know any better and will unnecessarily tear down and rebuild the <li>Duke</li> and <li>Villanova</li> subtrees between the renders.

A world with keys

Suppose your list had the following trees instead:

// First render
<ul>
  <li key="2015">Duke</li>
  <li key="2016">Villanova</li>
</ul>

// Second render
<ul>
  <li key="2014">Connecticut</li>
  <li key="2015">Duke</li>
  <li key="2016">Villanova</li>
</ul>

Now, React can figure out that the subtree with the key '2014' is the only new subtree, and the subtrees with keys '2015' and '2016' from the previous tree still exist. This means it saves itself the work of tearing down and rebuilding two subtrees as it builds the virtual DOM based on the new tree.

It will still need to recursively walk through the '2015' and '2016' subtrees to determine if any props or children have changed, but thanks to the key prop, at least it won’t have to unnecessarily tear them down and rebuild them.

That might seem like only a small bit of work, but it can provide significant performance gains if you ‘re working with a very large list or a list that is updated frequently.

Other notes

  • Keys only need to be unique among sibling elements of an array. They don’t need to be globally unique. For example, you can have multiple elements with the key foo as long as they are inside different arrays.
  • Using indexes as keys is discouraged.

Sources

Tagged: React

Leave a comment

Your email address will not be published. Required fields are marked *