Table of contents
1.
Introduction
1.1.
What is reconciliation?
2.
Virtual DOM in React Reconciliation
3.
How are updates decided in Reconciliation?
4.
Effects on the DOM elements and their attributes
5.
The Keys and Rerenders in React Reconciliation
6.
Diffing Algorithm in Reconciliation
6.1.
Having elements of Different Types
6.2.
Having DOM Elements of Same Type
6.3.
Recursing Over the Children
6.4.
Keys
7.
The shortcomings of React Algorithm
8.
Frequently Asked Questions
9.
Key Takeaways
Last Updated: Mar 27, 2024

React Reconciliation

Author Sneha Mallik
0 upvote

Introduction

The choice to re-render the component is decided using React's "reconciliation" process. DOM(Document Object Model) manipulation in the browser is costly and time-consuming when mounting and unmounting. The react reconciliation process is one factor that contributes to its high performance.

In a nutshell, it looks for differences and updates the DOM only when necessary, attempting to update only the portions that need to be modified.

Also See, Dropdown in React JS, Hooks in React JS

What is reconciliation?

Reconciliation in react is a procedure that uses a declarative API(Application Programming Interface) to keep you from having to worry about what's changing with each update. When the state of a component changes, React must decide whether or not to update the DOM.

It produces a Virtual DOM and compares it to the current DOM during this procedure. The new state of the DOM will be stored in the Virtual DOM in this case.

Reconciliation creating a Virtual DOM and comparing to the current DOM

Virtual DOM in React Reconciliation

React generates a theoretical DOM tree called the Virtual DOM when a component's state is changed. This is modelled after the state of React application on modification of the state, such as after calling this,  setState().

To do the comparison and analysis between the DOM before and after the update, React uses a system called a "snapshot." This is the point at which React reconciliation mechanism comes in.

Since the browser does not need to display a view of the Virtual DOM, updating it is much faster than updating the real DOM.

How are updates decided in Reconciliation?

When the component level state is modified, the reconciliation process is performed. It compares the current DOM to the Virtual DOM to determine which modifications to the real DOM are required. It then runs the render method after determining which DOM nodes in your application need to be updated.

Effects on the DOM elements and their attributes

The react reconciliation algorithm examines individual characteristics in addition to entire DOM elements. Let us consider the difference between a PUT and a PATCH request: a PUT request just updates the bits that have changed, whereas a PATCH request updates the complete object if there has been a change. It is similar to the concept of reconciliation. In reconciliation, react produces a Virtual DOM and compares it to the current DOM during this procedure, like a PUT request. The new state of the DOM is then stored in the Virtual DOM.

While it does not always have to unmount and remount the whole element, it does so occasionally. If we render an element of a different type, this will be another example of this.

Consider the case where we needed to toggle between two components or elements, possibly for conditional rendering. Regardless of whether or not they include the same child nodes, this would result in a complete unmounting of the component.

This differs from changing characteristics on the same type of element based on component status, such as dynamic class names. The DOM element is not deleted in this case; just the modified attributes are updated. This is beneficial since it performs only the most essential actions on the DOM, which, as we all know, consumes more resources than conventional object operations.

The Keys and Rerenders in React Reconciliation

In React, the "key" attribute can be used to indicate whether a DOM node is stable or not. If you've ever tried to map over a collection without a key and to return a JSX element in each iteration, you may have noticed a message in the console. The message gives us a warning that a key should be provided for the collection of items. This is because the reconciliation process relies on the keys to detect whether or not the content has changed, and failing to include a key may result in unexpected behavior. As a result, the keys should be distinct so that reconciliation can distinguish between which components are stable and which are not.

Consider the following scenario: you have a list of items generated from an array. If you insert one item into the middle of it, all of the succeeding elements' indices will be changed. Since the keys will not be consistent, and there will be a unique representation of each item in this circumstance and hence, it may wind up altering the unintended item, causing severe issues.

Diffing Algorithm in Reconciliation

When a component's state changes, React first checks the root elements of both trees to see if an element has to be changed from one type to another. Then react unmounts the entire tree and replaces it with the new one.

The nodes of an old tree will be destroyed during an unmounting of a tree. The component instance will receive the componentWillUnmount() lifecycle method, and any state associated with the old one will be lost.

The new DOM replaces the old one throughout the process of creating a new tree, and the component instance will receive another lifecycle method named componentWillMount(), followed by componentDidMount(). Any node found below the root of a DOM tree will be deleted in this situation.

There are different types of Diffing Algorithm:

Having elements of Different Types

Original DOM

<h1> Welcome to Coding Ninjas! </h1>

New DOM

<p> Welcome to Coding Ninjas! </p>

The Old DOM is deleted in this situation, and a new one is created in its place.

 

Having DOM Elements of Same Type

Original DOM

<h1 className = ”old”> Welcome to Coding Ninjas! </h1>

New DOM

<h1 className = ”new”> Welcome to Coding Ninjas! </h1>

React just changes the classname on the underlying DOM node, which goes for the style attribute in this example.

 

Recursing Over the Children

React iterates over both lists of children at the same time when recursing on the children of a DOM node by default and generates a modification whenever there is a difference.

Original DOM

<ul>

<li>Item 1</li>

<li>Item 2</li>

</ul>

New DOM

<ul>

<li>Item 1</li>

<li>Item 2</li>

<li>Item 3</li>

</ul>

React will match both the list and the children; inserting the new child in the list is displayed in the new DOM.

 

Keys

React provides another mechanism called keys, which we utilize when putting the children at the front of the list. If we consider the Type 3 example above, adding <li> Item 3 </li> to the children elements’ top will result in the poorest performance because it will traverse/mutate every child.

To address this situation, react provides an attribute called Keys, which is critical in fixing the problem. When children have keys, react uses the key to link children in the original tree with children in the following tree.

Original DOM

<ul>

<li key = “one”>Item 1</li>

<li key = “two”>Item 2</li>

</ul>

New DOM

<ul>

<li key = “three”>Item 3</li>

<li key = “one”>Item 1</li>

<li key = “two”>Item 2</li>

</ul>

In this example, React detects that the list element with key="three" was inserted as a new element, while the others remained unchanged, resulting in improved performance.

 

Even if we add item 3 to the top of the list of Original DOM children, it will be reasonable and efficient if we add the key attribute.

The shortcomings of React Algorithm

Let us consider a list of items. It may have hundreds of similar nodes that can be changed and rearranged. If we rearrange them, the Reconciliation algorithm will not have an idea which ones go in which of the two trees, resulting in a full re-render. This is where the importance of the key becomes evident. If each list item has a unique key, the algorithm will not match them between trees. This is why an array index or a random number should never be used as a key. If you use an index then rearrange the objects, the indexes will change. The algorithm will incorrectly match the nodes, causing your UI to act unpredictably. Nothing will break if you use random integers generated on each render. However, it will be wasteful because every node will be constructed from scratch on each render.

Frequently Asked Questions

  1. In React, how does reconciliation work?

Ans: The mechanism by which React modifies the DOM is known as reconciliation. When the state of a component changes, React must determine whether or not it is essential to update the DOM. It accomplishes this by generating a virtual DOM and comparing it to the actual DOM. In this case, the virtual DOM will hold the component's updated state.

 

2. What is the "key" prop, and why is it useful in arrays of elements?

Ans: When generating arrays of elements, you should add a key as a special string attribute. React uses the key prop to determine which items have been modified, added, or removed.

 

3. What is the Virtual DOM, and how does it work?

Ans: The Virtual DOM (VDOM) represents Real DOM stored in memory. The memory representation of a user interface is kept in sync with the "actual" DOM. It's a step between the call to the render function and displaying elements on the screen. The term "reconciliation" refers to the entire procedure.

There are three basic steps to using the Virtual DOM.

  • The entire UI is re-rendered in Virtual DOM representation whenever any underlying data changes.
  • The difference between the old and new DOM representations is then calculated.
  • After the calculations are completed, the real DOM is updated to reflect only the changes that occurred.

Key Takeaways

In this blog, we have learned the concepts of React reconciliation. The two most important lessons for understanding how React's reconciliation approach works:

  • React can speed up your UI. It's beneficial to comprehend the process of reconciliation.
  • React does not re-render all of your DOM nodes. It just modifies what is required. You might overlook the diffing procedure because it happens so quickly.

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of React reconciliation of Web Development. 

Credits: GIPHY

Happy Developing!

Live masterclass