Open In App

What is Diffing Algorithm ?

Last Updated : 13 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Diffing Algorithm in React JS differentiates the updated and previous DOM of the application. DOM stores the components of a website in a tree structure. React uses virtual DOM which is a lightweight version of the DOM. The only difference is the ability to write the screen like the real DOM, in fact, a new virtual DOM is created after every re-render.

What is Diffing Algorithm in React ?

Diffing short for Differences Algorithm is used to differentiate the DOM Tree for efficient updates. React utilize diffing algorithm to identify the changes in the newly created virtual dom and previous version of dom after any changes are made.

How Diffing Algorithm Works?

  • First, the content is rendered on the webpage and the DOM tree is created.
  • On change in any content due to user interaction or change in data from API,React works on observable patterns, hence, whenever there is a change in the state, it updates the nodes in the virtual DOM
  • In reconcilliation the old tree is compared to the newest version to determine the number of changes needed for updation.
  • After determining the changes a set of optimized and minimal instruction is created to implement on the real DOM.
  • These changes are then implemented and only content that changed is re-rendered on the web pages.

Assumption for Diffing Algorithm

React uses a heuristic algorithm called the Diffing algorithm for reconciliation based on these assumptions:

  • Elements of different types will produce different trees
  • We can set which elements are static and do not need to be checked.

React checks the root elements for changes and the updates depend on the types of the root elements,

  • Element in different types: Whenever the type of the element changes in the root, react will scrap the old tree and build a new one i.e a full rebuild of the tree.
  • Elements of the same type: When the type of changed element is the same, React then checks for attributes of both versions and then only updates the node which has changes without any changes in the tree. The component will be updated in the next lifecycle call.

Note: This is the reason why we should always use unique keys in the elements so that it will be easy for React to determine changes in the elements.

Advantages of Diffing Algorithm:

  • It enables efficient updates and reduce the work need to reflect the changes
  • It enhance the performance by updateing only the required components/ nodes.
  • Results in faster respose while change by reducing the unwated and unnecessary re-renderings.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads