Skip to main content

Command Palette

Search for a command to run...

Getting Started with React: A Comprehensive Introduction

Updated
8 min read
Getting Started with React: A Comprehensive Introduction
S
Hi, I am Shivang Yadav, a Full Stack Developer and an undergrad BTech student from New Delhi, India.

Introduction to React

What is React?

React is an open-source JavaScript library for developing interactive user interfaces (UI), commonly used in making single-page applications (SPAs). It was built and is maintained by Facebook

React is based on a components-based approach to build complex user interfaces. React components are self-contained, reusable building blocks for creating user interfaces. These components can be combined to create complex user interfaces while maintaining a clear and structured codebase.

e.g. Imagine a web page as a collection of small-small blocks. Each small block represents a component, such as a header, a navigation menu, or a content section. React helps you build and assemble these small blocks to create a complete web page.

Why use React?

What is the need for React when JavaScript already exists?

You may wonder why React was developed when JavaScript already exists. To understand this, it's essential to recognize that React is not a replacement for JavaScript but rather a library built on top of it. JavaScript is the core programming language used for web development, but React addresses specific challenges and needs in the context of building user interfaces.

Challenges in Traditional Javascript that React solved -

  • JavaScript employs an imperative programming approach, where developers specify how to achieve a particular functionality step by step. In contrast, React adopts a declarative approach. In React, developers specify what functionality they want, and React automatically manages the underlying procedures to achieve the desired outcome.

  • When working with JavaScript, directly interacting with the Document Object Model (DOM) can lead to inefficiencies in website performance. React addresses this issue by introducing the Virtual DOM. Instead of manipulating the Real DOM directly, React updates a Virtual DOM representation first. Then, it compares this Virtual DOM to the Real DOM, using a diffing algorithm to calculate the minimal steps required to update the Real DOM.

  • React's component-based approach enhances code reusability and promotes structured and readable code. Unlike vanilla JavaScript, where code can become complex and hard to maintain, React allows developers to create modular and reusable components, making it easier to build and maintain large-scale applications.

Virtual DOM vs. Real DOM

The real DOM is a representation of a webpage that you view in your browser. It's a tree-like structure that represents all the elements on a webpage - text, images, buttons, and so on.

In contrast, the virtual DOM serves as a blueprint of the real DOM, but it exists only in the computer's memory, not on the actual webpage you're looking at. It's like a sketch of the webpage.

Here's a simplified analogy to help understand the Virtual DOM:

  • Imagine the real DOM as a physical book in a library. If you want to make changes to the book, you need to physically go to the library, make the edits, and then put the book back in its place.

  • Now, think of the Virtual DOM as a digital PDF of the book. You can make as many changes as you want to the PDF without affecting the original book. When you're done, you can compare the edited PDF with the original book and apply only the necessary changes to the actual book.

In this analogy, the PDF serves as a lightweight, editable representation of the original book, just as the Virtual DOM serves as a lightweight, editable representation of the real DOM.

Declarative Nature of React

React follows a declarative approach to building user interfaces. Instead of manually instructing how the UI should change when data changes, you declare what the UI should look like for a given state, and React takes care of updating it accordingly. You don't need to provide step-by-step instructions on how to render each component or handle every user interaction. You only state, "This is how the UI should look given the current data". This makes the code more predictable and easier to understand.

e.g. Imagine you're ordering a cake. Imperative programming is like giving a recipe with step-by-step instructions to bake it yourself. You're telling exactly what to do. On the other hand, Declarative programming is like ordering from a bakery. You just say, "I want a delicious cake," and they handle everything, using their expertise to make it happen.

In React, it's similar. You declare what you want your UI to look like, and React figures out how to update it efficiently. This declarative approach simplifies development by focusing on the "what" instead of the "how," making your code more maintainable and scalable.

Understanding Components in React

What are React Components?

In React, components are the building blocks of a user interface. They are reusable, self-contained pieces of code that can be composed to create complex UIs.

Think of React components as the basic building blocks for making a website, similar to how bricks are the essential pieces for building a house. Each React component is like a small, self-contained part of a webpage that can be used to create more complex web applications.

Imagine you're building a web application. Instead of trying to make the whole thing in one piece, you use different blocks for different parts – one block for a button, another for a header, and yet another for a form. These blocks (components) can be used in different different parts of the application.

By breaking down your webpage into these reusable components, you make your code more organized and easier to work with. If you want to change something, you can focus on just one component without messing up everything else. It's like rearranging or replacing specific Lego blocks without affecting the entire structure. This makes your code easier to maintain and build upon as your project grows.

Functional Components vs. Class Components?

React components are of two types functional components and class components.

  • Functional components are stateless, meaning they don't manage their own internal state. They are simpler and more concise than class components. They consist of a function that takes props as an argument and returns JSX(JavaScript XML) to render.
import React from 'react'

function App() {
  return (
      <div>App</div>
  )
}
export default App

But in recent versions of React, functional components are favored and can also manage state using react-hooks, making them more concise and easier to understand.

  • Class components on the other hand can hold and manage their own internal state. This allows them to store and update data that can affect the component's rendering.
import React, { Component } from 'react'

export class App extends Component {
  render() {
    return <div>App</div> 
  }
}
export default App

Class components have lifecycle methods like componentDidMount, componentDidUpdate, and componentDidUnmount that you can use to manage component behavior throughout its lifecycle. However, with the introduction of React hooks in functional components, many of these lifecycle methods can be replicated using hooks like useEffect.

The Shift to Functional Components with Hooks:

In recent versions of React, functional components have gained significant enhancements through the introduction of hooks. Hooks are functions that allow functional components to manage state, side effects, and other React features that were previously exclusive to class components. This shift has made functional components more powerful and flexible.

import {useState, useEffect} from 'react'
function App() {
     //useState hook
     const [state, setState] = useState()
     //useEffect hook
     useEffect(() => {
       return () => {  }
     }, [])
  return (
      <div>App</div>
  )
}
export default App

Commonly used hooks include:

  1. useState: This hook allows functional components to declare and manage component-level state.

  2. useEffect: It enables functional components to perform side effects, such as data fetching, after the component has rendered.

  3. useContext: This hook provides access to the context API, allowing components to access global state without the need for prop drilling.

Handling Data with Props and State

Passing Data with Props

Props (short for properties) are a way to pass data from parent components to child components in React. They are read-only and help in creating dynamic and reusable components by allowing you to customize their behavior and appearance.

e.g. Think of props as parameters you pass to a function. For instance, you can pass a "color" prop to a button component to specify its color.

Managing Component State

State in React is used to store and manage data that can change over time. Stateful components can update their state and trigger re-renders, allowing your UI to react to user interactions and data changes.

e.g. Consider a weather app. The temperature displayed is a piece of state that updates as new data becomes available. When the temperature changes, React automatically updates the UI to reflect the new value.

State vs. Props: When to Use Each

Understanding when to use state and when to use props is crucial in React development. Props are used to pass data from parent to child components, while state is used for managing data that can change within a component.

Conclusion

In conclusion, React is a powerful library for building user interfaces in JavaScript. It simplifies UI development by introducing the concept of components, uses a Virtual DOM for efficient updates, and promotes a declarative approach to building UIs. Understanding components, props, and state is essential for building interactive and dynamic web applications using React.

By mastering React's concepts and principles, you can create scalable, maintainable, and highly performant web applications that provide a great user experience.

More from this blog

S

Shivang Yadav

16 posts