This algorithm is used by react.js underhood to carry out the reconciliation process with ease.

It works with 2 assumptions :

  1. If any two elements change they will be creating two different trees.

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.

  1. When working with a list of child elements which often changes, should be provided with a unique “key” as a prop.

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:

Screenshot from 2025-01-16 16-17-08.png

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.