Essential concepts for understanding React

Essential concepts for understanding React

·

2 min read

React is one of the most in-demand JavaScript libraries today. If you want to become a React developer, here are a few concepts that will give you a better understanding of how the library works. Let’s get started!

React uses a declarative approach

In this kind of approach, we just have to tell React what has to be done. That’s it! React does the work for us on its own. Whereas if you use plain JavaScript, you will have to give many commands to modify the DOM (Document Object Model) tree.

Let’s take the simple example of a counter updater.

If use plain JavaScript, this is what the code looks like:

Here 0 has an id counter

increment_button.addEventListener('click',()=>{
    document.getElementById('counter').textContent+=1
})

In the case of React, we use

const [counter,setcounter] = useState(0);

Inside the component return

<div>{counter}</div>
<button onClick={()=>{setcounter(counter+1)}}>+</button>

Notice that the syntax is simpler and more understandable to anyone who has no idea of React.

Component Rendering concepts

We write all the JSX code inside the return part of the functional component. It is exactly similar to writing HTML code on a simple HTML-only file and it works the same way as well. But, behind the scenes, React writes JavaScript code. For every div you add inside the component, React runs the React.createElement() command with some arguments about the type of tag, and the contents you give in it.

To check it, let's have a component HelloWorld

function HelloWorld(){
    return(
        <div>Hello World</div>    
)    
}

Now try this on your App.js file (by importing the component of course)

console.log(HelloWorld())

You will see this output on the console.

{$$typeof: Symbol(react.element), type: 'div', key: null, ref: null, props: {…}, …}

Here you can see, React has created an element for us of type div (<div>). If you expand this, you will see

props: {children: 'Hello World'}

This is all that runs behind every component we create.

Reconciliation

When the setState function is called and the state of a component is updated, React triggers the process of reconciliation. Both the actual web pages and React's lightweight representation - called the virtual DOM - are organised in tree structures. Changes made to the virtual DOM are compared to the previous version of the virtual DOM using a diffing algorithm, which identifies the difference between the two trees. React then minimizes the necessary changes to update the tree, ensuring efficient state updates for the components.

That’s it for today. Hope you got to learn something from this. I’ll see you soon. :)