How React Works Under the Hood

React is not a framework it’s a javascript library. We can import its built-in method and use it. React work with an entire network of tools all work together. Webpack, npm, node, J.S.X, and Babel. There are alternatives for tools but this is the most common use.

Photo by Malte luk from Pexels

J.S.X in React

It looks like everything in the HTML tag But this is all about Javascript. In react, app JSX babel preset will transform these expressions into actual Javascript code. Babel is typically used and recommended for transforming JSX expression.

//JSX
return (
<div className="title">
<h1>Hello World!</h1>
</div>
);

This is a simple JSX code inside the React component return method.

//Transform into Javascript code
return React.createElement(
"div",
null,
React.createElement("h1", { class: "title" }, "Hello World!")
);

In this way react babel preset transform JSX code into javascript code. After import, React create an element like JSX code using the createElement method The createElement accepts three-parameter first one for tag name as like HTML tag and second one attribute and last one for children.

Babel in React

A lot of browsers don’t support the very newest javascript features. This time works Babel to transforms the newest features into a backward-compatible version of JavaScript in current and older browsers or environments.

//ES6 code
const sum = (a,b)=>{
return a+b;
}
//Babel compile
var sum = function sum(a, b) {
return a + b;
};

But something else Babel does in React it transforms JSX code also into Javascript code. When we have JSX code babel it’s turned into React.createElement. it does this with react Babel preset. Babel is a tool but react has created a preset. You can check it on your root directory package-lock.json file. ref

package-lock.json

Webpack in React

In react, webpack traverse the tree go to the source folder and bundle file into a few files and also webpack dev server dependence take those files and bundle. also, hold them in memory and server to browser dom. So webpack bundle and server file into the browser. You can with browser sources.

devtools

Behind the DOM Update

The web browser has something called DOM(Document Object Model). it’s a representation of what we see on web browser. What react does it create a virtual version of DOM it’s literally called virtual DOM. When there are changed something in our application. it creates a new virtual DOM. then it compares within the previous virtual DOM. This time react uses diffing algorithm to look ar the difference between the old virtual DOM and the new version Virtual DOM. if it finds any difference then it updates actual DOM.

Virtual DOM diff Real DOM

Front End Developer