React & keys 🔑🔑🔑
Why do we need keys in React?
Well, the answer lies in efficiency and performance.
Let me explain...
I assume you prefer fast websites rather than slow ones. Who doesn't...
Let's dive deeper...
DOM & Virtual DOM
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)!
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 👋🏻