React Hooks, Reconciliation & Diffing Algorithm

Smit DesaiSmit Desai
4 min read

Everything React can do can be done using Normal JS HTML also. So why React.
\=> It makes your Developer Experience easy, Less code and do more. What else? We'll learn about it in this blog.

React gives you super powers so that you can make these Large Scalable Production Ready Performant applications and also Optimises something on webpage so things happen very fast

👉🏻 GOOD PRACTICES TO USE WHILE CODING IN REACT

https://legacy.reactjs.org/docs/faq-structure.html
If
you are making a components folders which has all component files

Try to Match the file name exactly with the the component name eg: Header in Header.js
You can use both Header.js or Header.jsx. It hardly matters. I use Header.js.
In industry people might use either of them so do not panic. It's the Same!

TRY TO KEEP THINGS SIMPLE

👉🏻 Never ever keep any hard coded data in your component folder.

<img src={"https://media-assets.swiggy.com/swiggy/image/upload/fl_lossy,f_auto,q_auto,w_660/"+food.imageId} alt="" />
The above URL is also a hardcoded string. Please avoid this and make seperate File for URLs

Use constants.js, utils.js any name of file works. But keep it separate. - A GOOD PRACTISE
Also naming those constants with CAPITAL LETTERS. eg: CDN_URL, LOGO_URL

👉🏻 Two Types of Export/Import

1. Using default a file can export only 1 thing eg: export default Header; And then import it import Header from "./components/Header";

2. But if you want to export more than 2 things (eg: constants) then you do not use default:
-> We use Named export
eg:
export const CDN_URL = "https://media-....";
export
const LOGO_URL = "https://t....jpg";
And then import where you want to use
import { LOGO_URL } from "../utils/constants";

Can you use Named with Default? Yes you can

👉🏻 Your Component's file in your app should be not more than 100 lines. It should be very short and clean.
Break down everything.

👉🏻 When we say React is Fast?
It means React is faster in DOM Manipulation. Updating the DOM efficiently
As the Data Layer Changes UI Layer should change accordingly. This is where REACT is BEST.

Whenever a state variable updates, React re-renders the component (React does it super fast)

To keep the UI Layer in-sync with Data Layer

👉🏻 Now Let's get Hooked

✔ What is Hook?
▪ Hooks are normal JavaScript function.
▪ Functions starting with use are called Hooks.

✔ What are the rules of using hook?
▪ Hooks must be declared at the of top level of component.
▪ Don't use hooks inside loop , conditions , nested function.
Only call Hooks from React function components , not from normal JavaScript function.

✔ What is useState hook?
▪ It is new way of creating variable.
▪ If we want to create local variable inside react, you need to use state variable and STATE VARIABLES are created using useState Hook.
▪ It returns an array.
▪ It has two parameters the first one is variable and second one is function which is used to update variable

✔ Why do we need state variable?
▪ Because when we create normal JavaScript variable and updates, it does not update the UI because react doesn't track it. That's why we need super powerful state variable(React keep track of it and when ever state variable change it will update the UI).

✔ Why do we need second argument inside useState hook?
▪ To refresh the page or to trigger the reconciliation algorithm and update the UI.

✔ What is virtual DOM?
▪ A lightweight object copy of the actual DOM. It is a Javascript Object representation. As it is made of React Elements.

✔ What is reconciliation?
▪ The process of updating the UI is knowns as reconciliation.

import RestaurantCard from "./RestaurantCard";
import { RES_LIST } from "../utils/mockData";
import { useState } from "react";


const ResNearYou =()=>{
  const [listOfRes, setListOfRes] = useState(RES_LIST);

  return (
    <div className="res-near">
      <h1>Restaurants near you</h1>
      <div className="filter">
        <button
          className="filter-btn"
          onClick={() => {
            const filteredRes = listOfRes.filter(
              (res) => res.info.avgRating > 4
            );
              console.log(filteredRes);
              setListOfRes(filteredRes);
          }}
        >
          Filter Restaurants
        </button>
      </div>
      <div className="res-container">
        {listOfRes.map((restaurants) => (
          // For each restaurants => return a (JSX) i.e <RestaurantCard /> (and pass data to it)
          <RestaurantCard key={restaurants.info.id} resData={restaurants} />
        ))}
      </div>
    </div>
  );
 }

 export default ResNearYou;

So whenever the STATE VARIABLE listOfRes is updates i.e when the setListOfRes is triggered it then triggers the Reconciliation algorithm which is achieved by using a diffing algorithm.

✔ What is Diff algorithm?
▪ It means finding the difference between older virtual DOM and new virtual DOM and then update the actual dom. Finding difference between Virtual DOMs are more efficient & faster as they are objects, while actual DOMs are html code.

✔ What is React Fiber?
▪ In react 16 react come up with new algorithm which is known as react fiber.
▪ React Fiber is the new reconciliation engine in React 16.

✔ Why React is fast?
▪ Because it does efficient and faster DOM manipulation.
▪ It has virtual dom.
▪ It has Diff algorithm which efficiently finds the diff between the old virtual DOM and new virtual DOM and then update the actual DOM(UI), this whole is known as react fiber.

This is why React is so POPULAR & Super Fast.

Useful Links:
https://github.com/acdlite/react-fiber-architecture

Stay Tuned for next blogs!!

0
Subscribe to my newsletter

Read articles from Smit Desai directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Smit Desai
Smit Desai