How ReactJS Works?

React is appears to be a very straightforward framework, but there are so many things going on under the hood. We are going to look into the following core concepts of React and how it works

  • JSX
  • Rendering
  • Updating state

JSX

The language that looks like HTML can create a react component is JSX (JavaScript XML). JSX is different than HTML. We cannot render it directly on a web page. JSX is an intermediate language created by React team. It allows us to write HTML code inside JavaScript. So, when you write

<div className=”test”>Hello world!</div>

React uses one of the core functions createElement to generate HTML from JSX. Here each attribute is converted into key-value pair. It happens internally but if you want to do it manually, here is a JS snippet generated from the above JSX.

React.createElement(“div”, {className: “test”})

This JS snippet will create an HTML Element as a JavaScript object So that you can use it in HTML later.

Rendering

After getting the HTML element from JSX, we must put it in DOM for which, we use the render method of ReactDOM, using which we can render HTML.

ReactDOM.render(<App />, document.getElementById(“root”))

render method takes two arguments: one is the JSX element that we want to render and second is the HTML element in which we want to render it. React uses one div with the id of “root” as a standard.

It will trigger the render cycle for the App component. If the App component has any other component as children, it’ll start their render cycles recursively.

Updating state

React is fast in updating the state and re-rendering the components. Whenever you update a state, the following things happen internally:

When we render something using ReactJS, it keeps a copy of DOM in its memory called Virtual DOM.

So, whenever we update the state of any component, it will generate a new copy of Virtual DOM. React will compare it with old Virtual DOM, and from that, it will find out the differences between both DOMs. It will decide what to render and what not to render from the difference. If any component requires re-rendering, it will re-render it and all of its children too.

Next time, if your page is re-rendering or misrendering and you are unsure about what is causing it, try to think about these topics. It may help you with your problem.

salman seikh

Salman has recently been part of GlobalVox . He is fond of coding and he is a Tech Savvy.
Salman Shaikh – Intern at GlobalVox | Posted on: January 6, 2022