In this post, I’m going to discuss how Angular and React differ in their change detection strategies.
A basic knowledge of both React and Angular is a prerequisite for this article.
Let’s get started.
CD is the process of detecting whether the application’s UI should be updated (and, if so, which parts to update) when changes to the underlying model come in through user interaction or through the network.
The process of CD is initiated any time one of the following happens:
setTimeout
.Notifications about timing and network events are made possible through a library called zone.js
.
Now, whenever any of the above events take place, Angular:
Bindings between HTML and TS properties
When the props to a component or the state of the component changes, render()
function is called, by default.
Every time render()
is called, React’s CD runs.
render()
is executed, React creates a virtual DOM object based on the JSX returned by render()
. The virtual DOM is called “virtual” because it’s a replica of the real DOM — a lightweight JavaScript replica object representing the data structures and data of the component.render()
is executed, a new version of the virtual DOM is created. This latest virtual DOM is compared with the immediately previous version, using a diffing algorithm.O(n)
time, making it really efficient. Based on whatever changes were detected by this diffing algorithm, a patch is created and scheduled to be applied to the real DOM.Updating the real DOM is much more expensive and time-consuming than updating the virtual DOM. This is because, while the virtual DOM is a lightweight JavaScript object (and it’s quick to update), updating the real DOM involves a lot of other processes too. Processes like processing and applying the CSS, setting the exact coordinates of all elements on the screen, traversing the DOM tree, rendering it, etc.
CD is the process by which the application’s UI and model stay in sync with each other.
Angular creates bindings between the HTML and TS, intercepts the calls to the registered event listeners, processes all bindings, and updates the DOM.
React keeps an eye on render()
. As soon as the latter is invoked, a virtual DOM object is created and compared with the previous version of the virtual DOM. Changes are calculated, batched, and a DOM update is scheduled.
#angular #react