DEV Community

Dalibor Belic
Dalibor Belic

Posted on • Originally published at blog.daliborbelic.com on

React & keys πŸ”‘πŸ”‘πŸ”‘

Well, the answer lies in efficiency and performance.

Let me explain...


I assume you prefer fast websites rather than slow ones. Who doesn't...

In terms of modern JavaScript frameworks, a significant factor for websites' performance is how efficient DOM updating is. In the case of React, we have something called Virtual DOM that addresses this problem.

Example: You have a list of 5 items. Let's say it's a list of todos. After you finish a task, and you'll check it off from the list. Now, most JavaScript frameworks would rebuild the entire list to show the updated one. And that’s 5 times more work than needed! Imagine you have a table with 1000 instances. You get the point...

Let's dive deeper...

DOM & Virtual DOM

As you probably know, DOM (Document Object Model) is the data representation of the objects that comprise the structure and content of a document on the web. It represents the page (as nodes and objects) so that programs (in our case, JavaScript) can change the document structure, style, and content. In React, for every DOM object, there is an equal virtual DOM object- like a lightweight copy.

Diffing

Let's get back to our example but analyse it from the React perspective: After you finish a to-do and check off the item from the list, the lightweight copy- virtual DOM- will completely update (which doesn't plunder the performance because updating virtual DOM is super fast). After the virtual DOM update, React compares the new one with the pre-updated one to determine precisely which element or more have changed in a process called diffing. And in the case of lists, as shown below, keys are the key (ba dum tss)!

code.png

Updating

Let's say we walked the dog. That todo has the id, therefore the key of 'id2' (because it's the second item in the todoList array). After diffing completes, React will know that only the HTML tag of 'li' with the key of 'id2' needs to be updated on the DOM. Without the key attribute, React couldn't know that, and it would update the entire list, which damages the performance, as we explained above.

And that pretty much sums it up. I hope you liked it. Feel free to reach out in the comment section below!

Till next time πŸ‘‹πŸ»

Dalibor

Top comments (0)