This algorithm is used by react.js underhood to carry out the reconciliation process with ease.
It works with 2 assumptions :
This seems obvious as there’s no rocket science behind this, but in react.js this may sometimes create a huge blunder when not kept in mind.
Now this asks for a detailed explanation cause, yeah it’s confusing at least for me for the first time.
So to pass a unique key there are two ways:
by passing it as an index,
by passing it as the index.id,
But why do we have to use a unique key, the reason behind this is simple to perform reconciliation, React's reconciliation process ****which is responsible for updating the UI.
During this, React lies on the key prop to uniquely identify each element in a list. This helps React determine:
If the key is not stable or unique, React might incorrectly associate items in the list, leading to:
Now let’s know why not to use just index as a key.
WHY IS index A BAD KEY?
Example:
const todos = [ { id: 1, name: "Buy groceries" }, { id: 2, name: "Walk the dog" }, ];
now user changes the order to:
const todos = [ { id: 2, name: "Walk the dog" },
{ id: 1, name: "Buy groceries" }, ];
In this react will check the key and find that the key has changed, which will result in displaying the wrong data to the user.