How React works behind the Scenes

How React works behind the Scenes

An Easy Guide to What's Happening Behind the Code

React components, elements, and instances

In React, a component is simply a function that returns a React element.

Take a look at this example:

const App = () => {
    return (
        <div>
           Miraya Tech
        </div>
    );
};

This component, App, returns a React element, which is an object referred to as an "instance".

When this code is executed, console.log(App()), it shows the underlying structure of the returned object (or instance):

{
    "$$typeof": Symbol(react.element),
    key: null,
    props: { children: "Miraya Tech" },
    ref: null,
    type: "div",
}

Let's break down this structure:

$$typeof: It's an internal property used by React to identify React elements.

type: The type of the element, in this case, it's a div.

props: Properties of the element, here children refers to the content "Miraya Tech".

key: A unique identifier for list items, not used in this example.

ref: A label for the element, also not used in this example.

The component is also a function that creates an element tree. When we render our component, React uses this function in the background using the assigned properties.

console.log(<App />)

// Output
{
    "$$typeof": Symbol(react.element),
    type: () => {...}, // This function is our component
    props: {children: "Miraya Tech"},
    key: null,
    ref: null
}

So, a Component Instance is the object that React generates when a component is displayed.

Each component has its own data (state) that can change and actions (lifecycle methods) that occur while the component exists.

React also provides us with hooks to manage the state and lifecycle methods of a Component Instance.

Reconciliation

Reconciliation is the process where React compares the virtual DOM with the real DOM and only updates the changed parts.

It uses a technique called diffing algorithm to that.

Diffing algorithm

It's a technique that React uses to compare the virtual DOM with the real DOM and spot the differences.

It analyzes elements structure and attributes to figure out what has changed.

This way, React can make updates only where needed, making it faster and more efficient.

Summary

  • React Components are functions that generate React Elements, which represent the UI and its properties.

  • React creates instances of components when they are rendered, and each instance has its own state and lifecycle methods.

  • Reconciliation is a process where React efficiently updates the DOM by comparing changes using the diffing algorithm.