Profile Photo

React JSX | Internal working

Created on: Jul 30, 2024

JSX, which stands for JavaScript XML, is a syntax extension for JavaScript used in React.js. It allows developers to write HTML-like code directly within JavaScript. This makes the code more readable and easier to write, as it enables the use of HTML tags to structure the component's UI.

Let's take a example from a project( check project in my github repo ).

// jsx/src/App.jsx const App = () => ( <div> <h1 className="abc">This is Heading 1 </h1> <h2 className="xyz">This is Heading 2 </h2> </div> ); export default App;

Above code get compiled to javascript code.

const App = () => React.createElement( "div", null, React.createElement("h1", { className: "abc" }, "This is Heading 1"), React.createElement("h2", { className: "xyz" }, "This is Heading 2") );

And the returned React Element is

{ type: "div", props: { children: [ { type: "h1", props: { className: "abc", children: "This is Heading 1", }, }, { type: "h2", props: { className: "xyz", children: "This is Heading 2", }, }, ], } }

We can check this by logging App in index.js

import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; const root = ReactDOM.createRoot(document.getElementById("root")); console.log("app value is"); console.log(App()); root.render( <React.StrictMode> <App /> </React.StrictMode> ); reportWebVitals();

jsx internal

Now comes rendering part. React creates a virtual DOM tree from the App component. The virtual DOM is an in-memory representation of the actual DOM elements. And when app starts initially, react renders entire Dom.

If app is already initialised and we do change, then React compares the virtual DOM tree with the previous virtual DOM to determine the minimal set of changes needed to update the real DOM. And render the the difference.