React Reconciliation

React Reconciliation

Hello guys, hope everyone is doing fine.

In today’s post, I’ll be talking about reconciliation in react. How it actually works under the hood and also the things we’ve been doing wrong while working with react.

ReactJS uses Reconciliation & diffing algorithm internally, through which React updates the DOM.

How the DOM is constructed?

Long story short talk, changing anything in DOM is expensive.
Especially, if we are changing multiple things at the same time in DOM.
Re-rendering in that scenario is gonna be super slow. So we have to be mindful whenever we are updating the DOM.

Now, this is the problem that Virtual DOM solves.

  • Instead of rendering all the changes to real DOM, react applies them to virtual DOM.
  • Virtual DOM doesn’t get re-rendered, So changes are cheap there.
  • React batches the changes together for efficiency.

The Virtual DOM

  • A lightweight representation of DOM
  • Exists in memory & is never actually rendered.
  • It’s just a tree data structure of plain javascript objects.
  • Popularized by React & also used by other frameworks like Angular 2 and Vue.

How does the Virtual DOM works?

  • Template language (JSX) tells the template compiler how to build an in-memory DOM tree.
  • render() function creates a virtual DOM tree of React Elements.

So, whenever the app is updated, either by calling setState() or by any other action. The DOM tree is rebuilt completely and at any given point there are two virtual trees that exist in memory at the same time.

This may sound wasteful, but it isn’t.
Now, React compares the two trees and maps out the differences between them and it’ll reconcile those differences. After that, it renders the changes to what we call the Actual DOM.
Also, it has to find the minimum no. of operations necessary to update the Actual DOM & then it batches the changes together.

Reconciliation

  • Finding the minimum no. of modifications required is an O(n³) complexity problem.
  • React uses a heuristic that is of complexity O(n).

Now it mainly relies on two assumptions in the algorithm.

Assumption 1

  • Two elements of different types will produce different trees.
    eg.

  • React will not attempt to find the diff between them, but will replace them completely.
  • It uses Breadth-First-Reversal while diffing the two trees.

Assumption 2

  • However, child elements may be hinted as stable across the renders with a key.
    eg.

In this case, even if we add a new element at the top React won’t render the whole list of items again. It’ll only render the one which was added later.
(Thanks to keys 😊)

To optimize performance the keys should be stable, predictable & unique.

A quick tip : Don’t use Math.random() while assigning the keys to elements.

Thanks, guys & have a good day!

Did you find this article valuable?

Support Nikhil Shinde by becoming a sponsor. Any amount is appreciated!