DEV Community

KIRUBAGARAN .K
KIRUBAGARAN .K

Posted on

Diffing algorithm in react

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.

  • Create a virtual representation of the UI
  • Compare old version vs new version
  • Update only changed parts in the real DOM

Think like this:

Old shopping list: Milk, Bread, Eggs

New shopping list: Milk, Bread, Butter

Example (real-life)

Diffing finds:

❌ Remove Eggs

➕ Add Butter

✅ Keep Milk, Bread

Only changes are applied

Diffing in React (important)

React uses a Virtual DOM and diffing algorithm.

Steps:

  • State changes
  • New Virtual DOM created
  • React compares old vs new Virtual DOM (diffing)
  • Finds minimal changes
  • Updates real DOM

Top comments (0)