DEV Community

Cover image for Introduction to React JS
Annapoorani Kadhiravan
Annapoorani Kadhiravan

Posted on

Introduction to React JS

Introduction

Applications like Facebook, Instagram, Netflix, WhatsApp Web, Amazon, and Gmail constantly update information without reloading the entire page. Notifications appear instantly, messages update in real time, shopping carts refresh automatically, and dashboards display live data.

Building such dynamic applications using plain JavaScript becomes increasingly difficult as the application grows.

This is where React.js comes into the picture.

React is one of the world's most popular JavaScript libraries for building fast, interactive, and reusable user interfaces.


History of React

Before React existed, developers primarily built websites using:

  • HTML
  • CSS
  • JavaScript (Vanilla JavaScript)
  • jQuery

These technologies worked well for simple websites where content rarely changed.

However, as web applications became larger and more interactive, managing the user interface became increasingly complex.

Imagine applications like:

  • Facebook News Feed
  • Instagram Timeline
  • Gmail Inbox
  • Online Banking Dashboard
  • Hospital Management System
  • Student Portal

Thousands of elements can change within seconds.

Updating each element manually using JavaScript quickly becomes difficult, repetitive, and prone to errors.

To solve this challenge, Jordan Walke, a software engineer at Meta (formerly Facebook), created React in 2011.

React was first used internally by Facebook before being released as an open-source JavaScript library in 2013.

Today, React is maintained by Meta along with thousands of contributors from the open-source community and is one of the most widely used frontend libraries in the world.


What is React?

React.js is an open-source JavaScript library used for building user interfaces (UI), especially for dynamic and interactive web applications.

Unlike traditional JavaScript, React allows developers to build applications using small, reusable pieces called components.

Instead of manually updating HTML elements whenever data changes, developers simply describe what the user interface should look like, and React takes care of updating the browser efficiently.

In simple words,

React is a JavaScript library that helps developers build fast, interactive, reusable, and maintainable user interfaces.


Why Was React Created?

To understand why React was created, let's first understand the problem developers faced before React.

Imagine you're building a simple score counter.

Initially, the webpage displays:

Score : 0
Enter fullscreen mode Exit fullscreen mode

Whenever the user clicks a button, the score should increase.

Sounds simple, right?

Now imagine you're building Facebook instead.

Every second, the application may need to update:

  • Notifications
  • Likes
  • Comments
  • Messages
  • Friend Requests
  • Posts
  • Advertisements
  • User Profile

Each of these updates requires modifying the webpage.

Before React, developers had to manually update every HTML element using JavaScript.

As applications became larger, this approach became difficult to manage.

Developers spent more time updating the UI than building new features.

React was created to solve this exact problem.

Instead of manually updating the webpage, React automatically updates only the parts that actually change.


Understanding the DOM

Before learning React, we need to understand one important concept:

DOM (Document Object Model)

Whenever a browser loads an HTML page, it converts that page into a tree-like structure called the DOM.

For example,

<body>

    <div>

        <h1>Welcome</h1>

        <p>Hello World</p>

    </div>

</body>
Enter fullscreen mode Exit fullscreen mode

The browser internally represents it like this:

Body
│
└── Div
     │
     ├── H1
     │      └── Welcome
     │
     └── P
            └── Hello World
Enter fullscreen mode Exit fullscreen mode

Every HTML element becomes a node inside this tree.

JavaScript interacts with this DOM whenever it needs to:

  • Create elements
  • Delete elements
  • Update text
  • Change styles
  • Add animations
  • Handle user interactions

The Problem with Direct DOM Manipulation

Imagine a webpage containing:

  • 500 buttons
  • 300 images
  • 200 forms
  • 1,000 text elements

Whenever one small value changes, JavaScript directly updates the browser's DOM.

Although this works, updating the real DOM is relatively expensive because the browser may need to:

  • Recalculate layouts
  • Repaint elements
  • Re-render portions of the page

For large applications, repeatedly updating the real DOM can impact performance and make the code harder to maintain.

React addresses this by reducing unnecessary updates to the real DOM.


What is the Virtual DOM?

One of React's biggest innovations is the Virtual DOM.

The Virtual DOM is a lightweight JavaScript representation (or copy) of the real DOM.

Instead of immediately updating the browser whenever data changes, React first updates the Virtual DOM.

Think of it like making edits to a rough draft before publishing the final version.

Instead of constantly changing the actual webpage, React first checks what has changed in this lightweight copy.

This approach significantly reduces unnecessary work.


Real-World Analogy

Imagine you're writing a school assignment.

You don't write directly on the final answer sheet.

Instead, you first write everything on rough paper.

You make corrections, erase mistakes, and improve your answers.

Only after you're satisfied do you copy the final version onto the answer sheet.

React follows a similar approach.

  • Rough paper → Virtual DOM
  • Final answer sheet → Real DOM

This allows React to make smart decisions before updating the browser.


How Does React Update the UI?

Whenever the application's data changes, React follows a simple process:

  1. Update the Virtual DOM.
  2. Compare it with the previous Virtual DOM.
  3. Find what has changed.
  4. Update only those changes in the real DOM.

This makes React much more efficient than repeatedly updating the browser directly.

But how does React know what has changed?

That's where the Diffing Algorithm comes in.


What is the Diffing Algorithm?

The Diffing Algorithm is React's comparison process.

Whenever state or props change, React creates a new Virtual DOM.

Now React has two versions:

  • Old Virtual DOM
  • New Virtual DOM

React compares both trees and identifies exactly which elements have changed.

For example,

Before clicking the button:

Score : 5
Enter fullscreen mode Exit fullscreen mode

After clicking the button:

Score : 6
Enter fullscreen mode Exit fullscreen mode

React notices that only the number changed.

The surrounding <div>, <button>, and other elements remain the same.

Instead of rebuilding the entire webpage, React updates only the changed text.

This comparison process is called the Diffing Algorithm.


Why is the Diffing Algorithm Important?

Imagine a webpage containing 5,000 HTML elements.

If only one button's text changes, rebuilding the entire page would waste processing power.

Instead, React compares the previous UI with the updated UI and changes only the affected elements.

This makes applications:

  • Faster
  • More efficient
  • Easier to scale

The larger the application becomes, the more beneficial this optimization is.


What is Reconciliation?

After the Diffing Algorithm identifies the differences, React updates the real DOM.

This updating process is called Reconciliation.

In simple words,

  • Diffing answers the question: "What changed?"
  • Reconciliation answers the question: "Apply those changes to the browser."

Instead of replacing the complete webpage, React modifies only the parts that actually changed.

This improves performance and provides a smoother user experience.


Complete React Rendering Flow

The following diagram summarizes how React updates the user interface.

User clicks a button
        │
        ▼
Application data changes
        │
        ▼
React creates a New Virtual DOM
        │
        ▼
Diffing Algorithm compares
Old Virtual DOM
        │
        ▼
Differences are identified
        │
        ▼
Reconciliation updates
only the changed elements
in the Real DOM
        │
        ▼
Updated UI appears instantly
Enter fullscreen mode Exit fullscreen mode

This entire process happens so quickly that users usually don't notice it.

That's one of the reasons React applications feel fast and responsive.


React is Declarative and Component-Based.


Imperative Programming

Before React, most web applications were developed using an Imperative Programming approach.

The word Imperative means giving instructions.

In this approach, the developer tells the computer every single step required to achieve the desired result.

Instead of describing the final UI, you manually explain:

  • What should happen first
  • What should happen next
  • Which HTML element to create
  • Where to place it
  • When to update it

In simple words,

Imperative Programming focuses on HOW to perform a task.


Imperative Programming Example (Vanilla JavaScript)

document.addEventListener('DOMContentLoaded', function() {

    // Create a new paragraph element
    const p = document.createElement('p');

    // Add text to the paragraph
    p.textContent = 'This paragraph was added imperatively with JavaScript.';

    // Find the content div and append the paragraph
    document.getElementById('content').appendChild(p);

});
Enter fullscreen mode Exit fullscreen mode

Let's understand what happens step by step.

  1. Wait until the webpage loads.
  2. Create a new <p> element.
  3. Add text to the paragraph.
  4. Search for the content div.
  5. Insert the paragraph inside that div.

Every action is performed manually.

Although this is simple for one paragraph, imagine updating hundreds or even thousands of elements in a large application.

The code becomes lengthy, repetitive, and difficult to maintain.


Declarative Programming

React follows a completely different approach called Declarative Programming.

Instead of explaining how to update the webpage, developers simply describe what the UI should look like.

React handles the implementation behind the scenes.

In simple words,

Declarative Programming focuses on WHAT the final user interface should look like.


Declarative Programming Example (React)

import React from 'react';

function App() {

    return (

        <div id="content">

            <p>This paragraph was added declaratively with React.</p>

        </div>

    );

}

export default App;
Enter fullscreen mode Exit fullscreen mode

Notice how much simpler this code is.

We don't tell React:

  • Create a paragraph.
  • Find the div.
  • Append the paragraph.

Instead, we simply describe the desired user interface.

React automatically creates and updates the necessary HTML elements.


Real-Life Analogy

Imagine you're ordering food in a restaurant.

Imperative Approach

You tell the chef:

  • Take a pan.
  • Add oil.
  • Cut onions.
  • Fry onions.
  • Add vegetables.
  • Add spices.
  • Cook for 20 minutes.

You're explaining every step.

Declarative Approach

You simply say:

"I'd like one Veg Biryani."

You describe the final result.

The chef knows how to prepare it.

React works in exactly the same way.

Developers describe the final UI, and React handles the implementation.


Imperative vs Declarative Programming

Imperative Programming Declarative Programming (React)
Focuses on How Focuses on What
Manual DOM updates Automatic UI updates
More code Less code
Harder to maintain Easier to maintain
Developer manages UI changes React manages UI changes
Better for small scripts Better for modern applications

What is JSX?

You may have noticed that React code looks similar to HTML.

For example:

<div>

    <h1>Welcome</h1>

    <p>Hello World</p>

</div>
Enter fullscreen mode Exit fullscreen mode

This syntax is called JSX.

JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like code inside JavaScript.

Although it looks like HTML, it is actually JavaScript.

Behind the scenes, React converts JSX into regular JavaScript before the browser executes it.

JSX makes React applications:

  • Easier to read
  • Easier to write
  • Easier to maintain

React is Component-Based

One of React's greatest strengths is its Component-Based Architecture.

Instead of writing one huge webpage, React encourages developers to divide the application into smaller reusable pieces called Components.

Think of components like LEGO blocks.

Each block performs one specific task.

When combined together, they create a complete application.

For example, a typical e-commerce website may contain:

App
│
├── Navbar
├── Search Bar
├── Banner
├── Product List
│      ├── Product Card
│      ├── Product Card
│      ├── Product Card
│
├── Shopping Cart
├── Footer
Enter fullscreen mode Exit fullscreen mode

Each of these is an independent component.


Creating Your First Component

// StaticMessage.js

import React from 'react';

function StaticMessage() {

    return <p>This is a static message!</p>;

}

export default StaticMessage;
Enter fullscreen mode Exit fullscreen mode

This component simply displays a paragraph.

Now let's reuse it.


Reusing Components

import React from 'react';

import StaticMessage from './StaticMessage';

function App() {

    return (

        <div>

            <StaticMessage />

            <StaticMessage />

        </div>

    );

}
Enter fullscreen mode Exit fullscreen mode

Instead of writing the same HTML multiple times, we simply reuse the component.

This is one of the biggest advantages of React.


Benefits of Components

Using components makes applications:

  • Modular
  • Reusable
  • Easy to maintain
  • Easy to test
  • Easier to understand
  • Easier to scale

Whenever you update one component, every place that uses it automatically reflects the latest version.


Parent Component and Child Component

React applications are built like a family tree.

One component can contain another component.

Example:

App
│
├── Header
├── Sidebar
├── Content
└── Footer
Enter fullscreen mode Exit fullscreen mode

Here,

  • App is the Parent Component.
  • Header, Sidebar, Content, and Footer are Child Components.

Parent → Child Communication

React follows One-Way Data Flow.

This means data naturally flows from the Parent Component to the Child Component.

The Parent passes data using Props.

Example:

<Header title="Welcome to React" />
Enter fullscreen mode Exit fullscreen mode

Here,

The Parent sends the value "Welcome to React" to the Header component.

The Child receives it and displays it.

This makes applications predictable and easier to debug.


Child → Parent Communication

Sometimes the Child Component needs to send information back to the Parent.

React does this using Callback Functions.

Instead of directly modifying the Parent's data, the Parent sends a function to the Child.

The Child calls that function whenever it needs to communicate.

Example:

Parent
   │
   ├── sends function
   ▼
Child
   │
   └── calls function
          │
          ▼
Parent receives updated data
Enter fullscreen mode Exit fullscreen mode

Although communication appears to move from Child to Parent, React's data flow still remains one-way because the Parent controls the data.


One-Way Data Flow

One of React's core principles is One-Way Data Binding.

Parent
    │
    ▼
Child
    │
    ▼
Grandchild
Enter fullscreen mode Exit fullscreen mode

Data always flows downward.

This makes applications:

  • Predictable
  • Easier to debug
  • Easier to maintain
  • Less prone to unexpected side effects

References :
https://medium.com/@castonboyd/react-js-for-beginners-understanding-the-why-mastering-the-how-and-exploring-the-what-2082aad56052
https://www.geeksforgeeks.org/reactjs/reactjs-introduction/
https://www.w3schools.com/react/react_intro.asp
https://strapi.io/blog/what-is-react-js

Top comments (4)

Collapse
 
dev_saravanan_journey profile image
Saravanan Lakshmanan

Detailed and Efficient explanation!

Collapse
 
annapoo profile image
Annapoorani Kadhiravan

Thank you!

Collapse
 
nimal_anand_51d0f3a2f1659 profile image
Nimal Anand

thanks, very simple and clear explanation with examples

Collapse
 
annapoo profile image
Annapoorani Kadhiravan

Glad to know!