React's diff algorithm

suggest change

Generating the minimum number of operations to transform one tree into another has a complexity on the order of O(n^3), where n is the number of nodes in the tree. React relies on two assumptions to solve this problem in linear time, O(n):

  1. Two components of the same class will generate similar trees, and two components of different classes will generate different trees.
  2. It is possible to provide a unique key for elements that is stable across different renders.

To decide whether two nodes are different, React treats these cases as different:

  1. Two nodes are different if they have different types.
  1. Whenever two nodes have different keys

Moreover, what follows is crucial and extremely important to understand if you want to optimise performance

If they [two nodes] are not of the same type, React is not going to even try at matching what they render. It is just going to remove the first one from the DOM and insert the second one.

Here’s why

It is very unlikely that a <Header /> element is going to generate a DOM that looks like what a <Content /> would generate. Instead of spending time trying to match those two structures, React just rebuilds the tree from scratch.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents