Open In App

Explain dirty checks in React.js

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Dirty Checks in React generally refer to the changes and modifications in the DOM if a component state is modified or dirtied and needs re-rendering making the React DOM updates efficient.

Prerequisites:

React uses virtual DOM to render the content. The DOM is an abstraction of a page’s HTML structure. It takes the elements and wraps them in an object with a tree structure. This provides an API that allows us to traverse the tree nodes and manipulate them such as adding nodes, removing nodes, or editing the contents of a node. DOM was intended for static UIs hence when the DOM updates, it has to update the node as well as the complete pages with their corresponding CSS and layout.

Dirty checks in React JS

DOM re-renders whenever there is a change in the data and it checks for data in two ways: 

  • Dirty checking: checks every node’s data at a regular interval to see if there have been any changes. Dirty checking is not the optimal solution as it requires traversing every single node recursively to make sure its data is up to date.
  • Observable: every component is responsible for listening to when an update takes place. Since the data is saved in the components state, they can simply listen to changes and update the changes if any.

React uses an observable technique whereas dirty checking is used in Angular.js.

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.

DOM updates in React:

  • On the first run, both virtual DOM and real DOM tree are created
  • React works on observable patterns, hence, whenever there is a change in the state, it updates the nodes in the virtual DOM
  • Then, react compares virtual DOM with the real DOM and updates the changes. This process is called reconciliation.
  • For reconciliation, it uses a diffing algorithm which is itself a dirty checking but it checks for virtual DOM changes instead of the data in real DOM nodes.


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

Similar Reads