WTF is a reconciler?
When you write your code in any framework and it updates stuff in the UI, all this is done behind the scenes by a reconciler. To understand reconcilers, you first need to know about virtual DOM , you can think of it as in-memory representation of real DOM. it reflects the desired state of UI.
whenever there is a state change in your app, react ( or other frameworks ) creates a new virtual DOM, and here reconcilers kick in.
How reconcilers work:
Diffing : reconcilers compare the old and new virtual DOM trees. using complex algorithms it identifies what needs to be added, removed, updated, moved in minimum steps within the DOM.
Patching : we don't directly apply the updates. it generates a minimal set of "patch instructions" specifying the precise changes needed.
Updating the real DOM : the reconciler applies the generates patches to the real DOM reflecting the latest UI state.
How React does reconciliation
The name of react reconciler is "Fiber ".
State changes : Changes in the applicatioin date due to API response, user interaction etc.
New Virtual DOM : React creates a new virtual DOM tree reflecting the updated state.
render
method is called on every component affected by state change.Diffing : The "Fiber" reconciler using fiber tree reconciliation algorithm, priority levels etc. compares the old and new DOM trees. It builds a tree of mutations describing the minimum changes needed to change the old DOM into the new.
Mutation batching : Instead of applying mutations immediately, Fiber groups them into batches for efficiency and minimising browser reapaints.
Prioritisation: Fiber prioritises mutations based on factors like urgency and user interaction which ensures essential UI updates happen fast, even if less critical tasks are still processing.
Fiber Tree Update : Fiber updates its internal "work-in-progress" tree with the mutations. This tree acts as a staging ground for applying changes to the real DOM gradually.
DOM Reconciliation: Finally, Fiber applies the accumulated mutations to the real DOM. This involves creating new nodes, deleting old ones, updating attributes, and reordering them as needed.
Optimising further :
Memoisation : using
memo
to skip re-rendering a component when its props are unchanged.Suspense:
<Suspense/>
lets components delay rendering until data is available, preventing UI glitches.Lazy Loading: Loading components only when needed reduces initial load times.
challenging react / making it more faster
million.js : Million.js makes react faster by skipping the diffing step entirely and directly updating the DOM nodes on a state change in the application.