How React works under the hood in details

YOUSSEF ALOUANI
8 min readAug 25, 2021
reactjs

in that last years React has become the most popular JavaScript library for building user interfaces . every week more than 10M new projects are started with react for build web apps .

from the NPM https://www.npmjs.com/package/react

react is a powerful tool for building web apps , but when we go deeply with react or when we start with react-testing-library , at this point you need to understand how react work . also if you wanna be a good developer you need to understand what happens behind the scenes , programming it is not just about coding it more deep than write some code , the most you understand the technologies you use the more smart and great you become .

for me if we want to understand how exactly react works we need to know how browsers works . so we will start with how the browsers works.

Browser

the browsers that we can use

the Browser is the most important program on your computer , it allows you to visit a website , from Wikipedia the browser is an application software for accessing the world wide web or the w3 , when a user request a web page from a particular website , the browser retrieves the necessary content from a web server and then display the pages on the user’s device .so how browsers works ?

how browsers works

main components of a browser

The browser main functionality is to present the web resource you choose, by requesting it from the server and displaying it on the browser window. The resource format is usually HTML but also PDF, image and more. The location of the resource is specified by the user using a URI (Uniform resource Identifier).The way the browser interprets and displays HTML files is specified in the HTML and CSS specifications. These specifications are maintained by the W3C (World Wide Web Consortium) organization .

in the image bellow you see The rendering engine : the engine responsible for displaying the requested content. For example if the requested content is HTML, it is responsible for parsing the HTML and CSS and displaying the parsed content on the screen , this engine contain a JavaScript interpreter ; Used to parse and execute the JavaScript code. and data storage and like all applications the browser use the cache and the RAM for works .

By default the rendering engine can display HTML and XML documents and images

The DOM

the browser show to the user a content this content need to be modified , styled and to deal with this . browsers needs to choose a specific format for this content . so they choose the DOM : the Document Object Model, a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The Document Object Model provides a standard model of how the objects in an XML or HTML document are put together and a standard interface for accessing and manipulating these objects and their inter relationships. Vendors can support the DOM as an interface to their proprietary data structures and APIs, and content authors can write to the standard DOM interfaces rather than product-specific APIs, thus increasing interoperability on the Web.

Document object Model

the flow rendering

the main flow of render the view

by default the The rendering engine will start getting the contents of the requested document from the networking layer. This will usually be done in 8K chunks.

The rendering engine will start parsing the HTML document and turn the tags to DOM nodes in a tree called the “content tree”. It will parse the style data, both in external CSS files and in style elements. The styling information together with visual instructions in the HTML will be used to create another tree : the render tree

The render tree contains rectangles with visual attributes like color and dimensions. The rectangles are in the right order to be displayed on the screen.

After the construction of the render tree it goes through a layout process. This means giving each node the exact coordinates where it should appear on the screen. The next stage is painting the render tree will be traversed and each node will be painted using the UI backend layer.

It’s important to understand that this is a gradual process. For better user experience, the rendering engine will try to display contents on the screen as soon as possible. It will not wait until all HTML is parsed before starting to build and layout the render tree. Parts of the content will be parsed and displayed, while the process continues with the rest of the contents that keeps coming from the network.Parsing a document means translating it to some structure that makes sense . the parsing is done with the parsing algorithm that use a diffrent approach than the top-down approach . The algorithm consists of two stages : tokenization and tree construction.Tokenization is the lexical analysis, parsing the input into tokens. Among HTML tokens are start tags, end tags, attribute names and attribute values.The tokenizer recognizes the token, gives it to the tree constructor and consumes the next character for recognizing the next token and so on until the end of the input.

the main flow

Tree construction algorithm

When the parser is created the Document object is created. During the tree construction stage the DOM tree with the Document in its root will be modified and elements will be added to it. Each node emitted by the tokenizer will be processed by the tree constructor. For each token the specification defines which DOM element is relevant to it and will be created for this token. Except of adding the element to the DOM tree it is also added to a stack of open elements. This stack is used to correct nesting mismatches and unclosed tags. The algorithm is also described as a state machine. The states are called “insertion modes”

HTML and Scripts

A client-side script is a program that may accompany an HTML document or be embedded directly in it. The program executes on the client’s machine when the document loads, or at some other time such as when a link is activated. HTML’s support for scripts is independent of the scripting language.

Scripts offer authors a means to extend HTML documents in highly active and interactive ways. For example:

  • Scripts may be evaluated as a document loads to modify the contents of the document dynamically.
  • Scripts may accompany a form to process input as it is entered. Designers may dynamically fill out parts of a form based on the values of other fields. They may also ensure that input data conforms to predetermined ranges of values, that fields are mutually consistent, etc.
  • Scripts may be triggered by events that affect the document, such as loading, unloading, element focus, mouse movement, etc.
  • Scripts may be linked to form controls (e.g., buttons) to produce graphical user interface elements.

and for that we use JavaScript , when JS was born it was used just for the client-side scripting . by the manipulation of the DOM with JS gives us the opportunists to make complex user interfaces and actions for that many javascript libraries like Jquery or React for example .

Starting With React

in the Development process we work with this file and from this file we create our app

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><link rel="icon" href="%PUBLIC_URL%/favicon.ico" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="theme-color" content="#000000" /><metaname="description"content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /><!--manifest.json provides metadata used when your web app is installed on auser's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/--><link rel="manifest" href="%PUBLIC_URL%/manifest.json" /><!--Notice the use of %PUBLIC_URL% in the tags above.It will be replaced with the URL of the `public` folder during the build.Only files inside the `public` folder can be referenced from the HTML.Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" willwork correctly both with client-side routing and a non-root public URL.Learn how to configure a non-root public URL by running `npm run build`.--><title>React App</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><!--This HTML file is a template.If you open it directly in the browser, you will see an empty page.You can add webfonts, meta tags, or analytics to this file.The build step will place the bundled scripts into the <body> tag.To begin the development, run `npm start` or `yarn start`.To create a production bundle, use `npm run build` or `yarn build`.--></body></html>

and we manipulate this HTML file with the index.js file

import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals';ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,document.getElementById('root'));// If you want to start measuring performance in your app, pass a function// to log results (for example: reportWebVitals(console.log))// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

the App file is our Component

import logo from './logo.svg';import './App.css';function App() {return (<div className="App"><header className="App-header"><img src={logo} className="App-logo" alt="logo" /><p>Edit <code>src/App.js</code> and save to reload.</p><aclassName="App-link"href="https://reactjs.org"target="_blank"rel="noopener noreferrer">Learn React</a></header></div>);}export default App;

in the app file we integrate all the component needed in the user interface .

To understand the component you need to understand the atomic design : as all javascript frameworks and libraries the goal is to make a good UI/UX , and the more the developer divide interfaces to a small peaces the more he can manipulate , mange or update them the atomic design is to make each element works independently and makes the order of building not important at all that way we choose the components concept based on the atomic design .

How React Works

now things become more clear i think we can have a clear perspective about how react can works

previously we said the using the html file and by the parsing process the browser create the render tree and with the scripting we modify this tree , so react do the same things react create a tree for u using its virtual DOM , so based on the element you give to the app.js file the combinations of all the components make react able to create a virtual DOM , and based on the original tree that create by your browser in the first time . React re-construct the tree based on the difference between them because its push just the changes between the two trees .

--

--

YOUSSEF ALOUANI

junior software engineer , the performance if it was a person , intrested in microservices architecture and System Design . I believe in sharing Knowledge