How does react work?

How does react work?

As a developer we should know what react is doing behind the scenes. So, react is a javascript library to develop a user interface.

How react able to work on so many things so easily, without affecting UI?

What is react element and components?

const App = () => {
    return (
         <div>
               React Element 
       </div>
    )
}
// it gives on console.log(<App/>), it is object 
{
$$typeof: symbol(react.element) 
key:null
props : {children:"React Element"}
ref: null 
type: div
}

Babel converts JSX into react.createElement() on function call. Each of this function gives javascript objects similar to above.

This is why we have to always import React while working with JSX.

  • $$typeof => for security measure.
  • keys => is give below
  • props => contain information of children
  • type => represent tag for DOM

React Components

Function or class that gives output an element tree to the DOM. React calling the component behind the scenes.

{
typeof: Symbol(react.element)
key:null 
props: {}
ref:null 
type:() => {} // it is the function return by react components in DOM
}

function on return statement => output .React calls it directly with assigned props

class components on render statement => output . Creates a new instance of it and calls it on the render() method.

React elements create DOM node(HTML elements) and also component Instance . So here is the question is what is a component instance

React keep track of a component by creating an instance of it. Each instance has a lifecycle method and internal state for components.

Reconcilation

Important topics that work behind the working of the reconciliation process are :

Virtual DOM

React provides a declarative API, we have not to worry about how changes on every update. React creates a tree of an element. This process happens very fast because react elements are plain javascript. This happens when we call the render() method. The tree of elements is kept in memory it is the Virtual DOM.(copy of the Browser DOM).

What happens when we change or update the state?

New virtual DOM is created and compared with previous ones. But how comparison works react can not re-render the whole tree. React compares the trees and updates the DOM with the least number of steps. It can not check each element it will take O(n3) so it will be taking a lot of comparisons. For 1000 elements it will take in the order of one billion comparisons.

Diffing

virtual-dom.webp

So here comes diffing algorithm (heuristic algorithm O(n)), It works on two assumptions:

1. The element of different types will produce different trees. let's see how it works:

<div>                                            
     <p>hello user</p>                 
</div>   
// after changing element 
<div>
     <h1>hello user </h1>
 </div>

React will rebuild the tree inside div from scratch, old instances of the old tree are destroyed with the current state. Components will unmount.

<div className="aalo"/>
// after updating className
 <div className="bhaalo"/>

Attributes will be updated, and the state will be maintained. (component instances will be the same.)

<ul>
    <li>aalo</li>
    <li>bhaalo</li>
</ul>
// after update
 <ul> 
     <li>aalo</li>
     <li>bhaalo</li>
     <li>Kaalo</li>
</ul>

React will match aalo and bhaalo then update trees and the insert Kaalo.

but the problem comes when we insert the element first in react.

<ul>
    <li>aalo</li>
    <li>bhaalo</li>
  </ul>
// after update
 <ul> 
     <li>Kaalo</li>
     <li>aalo</li>
     <li>bhaalo</li>
</ul>

React will check every element and create a new tree, can keep aalo and bhaalo. It creates inefficiency, for 1000 elements will create a new tree again which is the problem.

2. Keys in react

Keys are attribute which is supported by react and should be a unique id. it should not be index. Solve the problem of inefficiency. Check elements if a new key is added or removed it will then update the tree.

<ul>
    <li key="aalo">aalo</li>
    <li key="bhaalo">bhaalo</li>
</ul>
// after update
 <ul> 
     <li key="Kaalo">Kaalo</li>
     <li key="aalo">aalo</li>
     <li key="bhaalo">bhaalo</li>
</ul>

it will only update Kaalo the new one and react will know key aalo and bhaalo are just moved.

Rendering in React

After react calculated all the changes to be made in the application, then rendering is handled by React DOM(for browser) and React Native (for mobile).

React is only the library that allows us to write react elements, components, states, and lifecycle methods and do diffing parts. React does not know whether it is in browser or mobile it gives expression to the app. you can create your own render by using the react-test-render-page.

Most of the implementation live in renders, but how it happens react communicates with render.

it looks like :

       const React = {
         __currentDispatcher:null,
          useState(intialState){
             return React._currentDispatcher.useState(intialState);
          } 
     }

when we call the useState the call is forward to currentDispatcher. ReactDOM sets this dispatcher.

    //inside react DOM 
    const previousDispatcher = React.__currentDispatcher; 
    React.__currentDispatcher = ReactDOMDispatcher ; 
    let result;
    try{
     result = component(props) // function    
    }  finally{
       React.__currentDispatcher = previousDispatcher ;
    }

Conclusion:

for working in react we should know how react works behind the scenes. cover the topics JSX, reconciliation, and rendering.

Blog for $$typeof link

If you find these blogs useful please share and also know your view please comment down below.