React: The Basics

Ashvin Choudhary
7 min readMay 19, 2023

React JS is today’s most popular JavaScript library for building User Interfaces, which has created by Facebook. We can build modern, fast Single Page Applications or websites with React. React is so popular in the market and beneficial to know for a Web/Frontend Developer.

Is React JS a Library or a Framework?

This is one of the most unclear subjects of React. Let’s make this clear from the beginning. React is a Library, not a Framework.

What is a Library?

A library in programming can be explained as a collection of codes. We use a library to write code in a much simpler way or to import a feature from it into our project. JQuery is a library for example. We can write JavaScript much simpler by using JQuery, or we can import written JQuery features to our project. The project itself is not dependent on a library.

A Framework, on the other hand, is a complete package of code with its own functionalities & libraries. A Framework has its own rules, you don’t have much flexibility and the project is dependent on the Framework you use. Angular is an example of a framework. So React is for building User Interfaces, and how you program the rest of the project is up to you. Like JQuery, you can include React in your project partially, or completely. So React JS is a library.

React Virtual DOM

To understand the importance of React Virtual DOM, first, you need to know what DOM (Document Object Model) is. DOM is basically a representation of the HTML code on a webpage. The document is the web page itself, the objects are the HTML tags. And finally, the model of DOM is a tree structure:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.

A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases. The Document Object Model (DOM) represents that same document so it can be manipulated. The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.

What is the benefit of Virtual DOM?

Each time you make a change in the code, DOM will be completely updated and rewritten. This is an expensive operation and consumes lots of time. In this point, React provides a solution: The Virtual DOM.

So when something changes:

  1. React first creates an exact copy of the DOM
  2. Then React figures out which part is new and only updates that specific part in the Virtual DOM
  3. Finally, React copies only the new parts of the Virtual DOM to the actual DOM, rather than completely rewriting it.

This approach makes a webpage much faster than a standard webpage. That’s also one of the reasons why React is so popular.

So what is this JSX?

JSX (JavaScript XML) is a syntax extension to JavaScript used by React. JSX is basically used to write HTML tags inside JavaScript. Later, the JSX code will be translated into normal JavaScript, by Babel.

In summary, React doesn’t have HTML files, HTML tags are rendered directly inside JavaScript. This approach makes React faster.

What is a React Component?

A component is an independent, reusable code block, which divides the UI into smaller pieces. In other words, we can think of components as LEGO blocks. Likewise, we create a LEGO structure from many little LEGO blocks, we create a webpage or UI from many little code blocks (components).

We don’t really want to have thousands of lines of code together in one single file. Maintenance of the code gets more and more complex as the project gets bigger. In this point, dividing the source code into components helps us a lot. Each component has its own JS and CSS code, they are reusable, easier to read, write and test. In web development, as the reasons I explained above, it’s beneficial to use component-based technologies, and React JS is one of them.

React has 2 types of components: Functional (Stateless) and Class (Stateful).

Functional (Stateless) Components

A functional component is basically a JavaScript (or ES6) function that returns a React element. According to React official docs, the function below is a valid React component:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

IMPORTANT: Functional components are also known as stateless components

So a React Functional Component:

  1. Is a JavaScript / ES6 function
  2. Must return a React element
  3. Take props as a parameter if necessary

Class (Stateful) Components

Class components are ES6 classes. They are more complex than functional components including constructors, life-cycle methods, render( ) function, and state (data) management. In the example below, we can see how a simple class component looks like:

import React, { Component } from 'react';

class ParentComponent extends Component {
return <h1>I'm the parent component.</h1>;
export default ParentComponent;
}

So, a React class component:

  1. It is an ES6 class and will be a component once it ‘extends’ React component.
  2. Can accept props (in the constructor) if needed
  3. Can maintain its own data with state
  4. Must have a render( ) method which returns a React element (JSX) or null

Let’s start by defining the Component’s props (obviously short for properties) in React. Props are used to customize the Component when it’s being created and give it different parameters.

import React, {Component} from 'react'

class Topic extends Component {
{this.props.name}
}

One of the most important features of props is that they can be passed by a parent component to its child components. This allows us to create a component that can be customized with a new set of props every time we use it.

import React, {Component} from 'react'

class Welcome extends Component {
<p> Welcome to React, today you will learn: </p>
}

Props are passed to the component and are fixed throughout its lifecycle. But there are cases when we want to use data that we know is going to change over time. In this case, we use something called state.

Unlike props, the state is a private feature and it strictly belongs to a single Component. The state allows React components to dynamically change output over time in response to certain events.

The component’s state is initialized inside a constructor:

class Counter extends Component{

constructor(props){
super(props);
this.state = {counter: 0}
<p>{this.state.counter}</p>
}

And can be changed later using the inbuilt setState() function

class Counter extends Component{

constructor(props){
super(props);
this.state = {counter: 0}
this.increment = this.increment.bind(this);
this.setState({counter: this.state.counter + 1})
<p>{this.state.counter}</p>
}

Lifecycle of Components

Each component in React has a lifecycle that you can monitor and manipulate during its three main phases.

The three phases are Mounting, Updating, and Unmounting.

Common React Lifecycle Methods

  • render()
  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()

The render() method is the most used lifecycle method. You will see it in all React classes. This is because render() is the only required method within a class component in React. As the name suggests it handles the rendering of your component to the UI. It happens during the mounting and updating of your component.

Now your component has been mounted and ready, that’s when the next React lifecycle method componentDidMount() comes in play. componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls if you need to load data from a remote endpoint.

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes. You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from the previous state. Incorrect usage of setState() can lead to an infinite loop.

As the name suggests this lifecycle method is called just before the component is unmounted and destroyed. If there are any cleanup actions that you would need to do, this would be the right spot.

Routing is a key aspect of web applications (and even other platforms) that could not be left out in React. We can make full-fleshed single-page applications with React if we harness the powers of routing. This does not have to be a manual process, we can make use of React-Router.

The switch component helps us to render the components only when the path matches otherwise it fallbacks to the not found component.

A <Router> that uses the HTML5 history API (pushState, replaceState, and the popstate event) to keep your UI in sync with the URL.

<BrowserRouter
basename={optionalString}
forceRefresh={optionalBool}
getUserConfirmation={optionalFunc}
keyLength={optionalNumber}>

Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string

Named Export vs Default Export in ES6

With named exports, one can have multiple named exports per file. Then import the specific exports they want to be surrounded in braces. The name of the imported module has to be the same as the name of the exported module.

// ex. importing a single named export

import { MyComponent } from "./MyComponent";

// ex. importing multiple named exports

import { MyComponent, MyComponent2 } from "./MyComponent";

// ex. giving a named import a different name by using "as":

import { MyComponent2 as MyNewComponent } from "./MyComponent";

// exports from ./MyComponent.js file

export const MyComponent = () => {}

export const MyComponent2 = () => {}

Default Export: (export default)

One can have only one default export per file. When we import we have to specify a name and import like:

import MyDefaultComponent from "./MyDefaultExport";

const MyComponent = () => {}

export default MyComponent;

You can just run the create-react app on the command line, followed by the name of the app you want to create. This creates the React app, with all the necessary functionality you need, already built into the app. Then you can just cd into the react app and start it with npm start.

Command: create-react-app my-app

node_modules is where packages installed by NPM or Yarn will reside.

src is where your dynamic files reside. If the file is imported by your JavaScript application or changes contents, put it here.

public is where your static files reside.

Originally published at https://www.tumblr.com.

--

--

Ashvin Choudhary

Ashvin Choudhary is an AWS Certified Senior Software Engineer with 8+ years of experience. He's enthusiastic about tech and believes in lifelong learning.