A Student's Guide to Software Engineering Tools & Techniques »

Introduction to React

Author: Aadyaa Maddi
Reviewers: Amrut Prabhu, Marvin Chin

What is React?

The official website describes React as follows:

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called 'components'.

React Features

Let us understand some key features of React with the help of an example. A web application that displays the name of a person is given below:

The sandbox above is editable. You can change the name using the textbox in the application and see how the UI automatically gets updated. You can view the application code by clicking the blue button next to "React: An Introductory Example".

Declarative Framework

The UI of a React application is defined using a mix of HTML code and HTML-like syntax, called JSX. The main view of the application above (defined in the App.render() method in index.js) is given as follows:

<div className="App">
  <h1>Person Data</h1>
  <PersonComponent
    name={this.state.name}
    changeHandler={this.handleChange}
  />
</div>

In the above example, we declare what we want to display (i.e. name) and React renders the appropriate view based on the updated application data. This is known as the Declarative programming focuses on what the program should accomplish without specifying how the program should achieve the result.declarative approach. With the declarative approach, you just need to specify what you want to show in the UI when the application data changes, rather than giving instructions on how to update the UI.

Components

React encapsulates application views and relevant data and logic for updating the views using components. A combination of components that exchange information with one another is used to build the UI of a React application.

For example, the application above is divided into two components:

  1. App

    The App component (defined in index.js) contains the main view of the application. It stores the application data (i.e. name) in an object called state and has a method to update the it every time the value in the textbox changes. It passes the application data and the method to the PersonComponent.

    function App() {
      const [name, setName] = useState("John Doe");
    
      const handleChange = event => {
        setName(event.target.value);
      };
    
      return (
        <div className="App">
          <h1>Person Data</h1>
          <PersonComponent
            name={name}
            changeHandler={handleChange}
          />
        </div>
      );
    }
    
  2. PersonComponent

    PersonComponent (defined in personComponent.js) renders the details of the person. It accepts input from the App component in the form of props.

    const PersonComponent = props => {
      return (
        <div className="Person">
          <h2>About Me</h2>
          <p>My name is {props.name}.</p>
          <label htmlFor="name">Name: </label>
          <input id="name" onChange={props.changeHandler} value={props.name} />
        </div>
      );
    };
    

As you can see, React components are just JavaScript functions that accept arbitrary input and return a declarative view describing what should appear in the application's UI.

One-Way Data Binding

Data binding refers to the exchange of information between the application data and the UI. React provides one-way data binding. In applications that use one-way data binding, changes to the application data are automatically reflected in the UI. However, changes to the UI need to be manually propagated to the application data.

In the above application, you can see that the UI is updated whenever a different name is entered in the textbox. These updates do not happen in a single step - the application data is first updated using the handleChange() method, and then the UI is updated to reflect these changes.

Why use React?

Now that we know what React is, let us look at some benefits it has to offer.

Benefit 1: Better Performance

Web applications can have a lot of user interaction and data updates, which results in changes being made to the The Document Object Model, or the 'DOM', is an interface to web pages. It represents the page as nodes and objects, allowing programs to read and manipulate the page's content, structure, and styles.DOM. Adding and removing DOM nodes isn't slow, but the performance-bottleneck arises because the browser needs to A reflow occurs when the structure of the DOM tree changes, and a repaint occurs on style changes. These operations can get quite expensive for large DOM trees.reflow and repaint the UI every time the DOM is changed.

React minimizes this update time by using a virtual DOM. The virtual DOM is a JavaScript object that is kept in the memory of your application.

Figure 1. How React's actual DOM gets updated.

As shown in Figure 1 above, updates to the UI will first be made to the virtual DOM. Then, React will compare the virtual DOM with the actual DOM using a diffing algorithm. Finally, React updates the actual DOM only in places it differs with the virtual DOM. It batches multiple changes together and updates the actual DOM in one go, minimizing update time.

Benefit 2: Abstraction

The traditional Imperative programming focuses on explicitly describing how a program operates.imperative approach of building a web application requires you to describe how you want your UI to change when your application data changes.

Most web applications usually have to interact with a lot of DOM elements and events. Also, different browsers have variations in their implementations of the The core DOM consists of the properties and methods of the DOM (nodeName, getElementById(), etc).core DOM, The events system consists of different kinds of events that the DOM supports (blur, change, etc).events system and even styles that can be applied to DOM elements! If you want your application to work across different browsers, you would need to manually take care of these variations with the imperative approach.

React's declarative approach simplifies this process because it abstracts the complexity of interacting with the actual DOM elements and events. For example, the virtual DOM helps React abstract browser-specific operations on DOM elements. Additionally, React provides its own events system so that events can work in the same way across different browsers.

Benefit 3: Testability

A React application is made up of a combination of components. Components are independent from each other, and like functions, they map the same input to the same output. This makes it easy to write unit tests for your application.

Additionally, React only allows data to flow downwards (one-way data binding) using state and props, which makes your application easier to debug as you can be sure that the data updates the UI, and never the other way around.

Other Advantages of React

Besides the three main benefits explained above, React has the following advantages:

  • React is not an An opiniated framework guides or locks you into their preferred way of doing things.opinionated framework, which gives you the flexibility to choose your application stack.
  • React is constantly being updated with new features (e.g. hooks were released in v16.8) and performance optimizations.

Disadvantages of React

Like any other framework/library, React has its share of disadvantages.

  1. Fast-Paced Development:
    The high pace of development of React means that you would need to regularly relearn how to do things.
  2. React is Just a UI library:
    As React only allows one-way data binding, you can't use it in applications that follow the MVC, or Model-View-Controller is a popular application structure for building web applications. It separates the UI and the data of your application, and changes can be made to your application using controllers.MVC architecture. You would have to use Flux, an application architecture that favors one-way data binding instead.

React and Other Competing Alternatives

There are a lot of JavaScript frameworks and libraries that you can use to build your next web application. Some popular alternatives to React are Angular and Vue.

How do you decide which one to use? Here are some resources to help you choose between them:

  • React, Angular, Vue: What they can do and which one is for you - This article has guidelines for choosing which technology to learn.
  • Angular vs Vue vs React - In addition to comparing the three technologies, this article aims to give a general structure for comparing JavaScript frameworks and libraries. Hence, you can use this structure to choose between any new frameworks that may arrive in the future.
  • State of JS 2018: Front-end Frameworks - This survey compares the average salaries, company size, developer satisfaction, etc. for the most used JavaScript front-end technologies, so you can decide which technology will be worth learning for a career in front-end software engineering.

Every framework has its pros and cons, but hopefully you have managed to see that React removes some of the complexity that comes with building user interfaces.

Getting Started With React

The official React website is a great place to get started. It includes:

  • A step-by-step tutorial for building a React application, if you prefer to learn by doing.
  • A guide to master the main concepts of React, if you prefer to learn by reading instead.

If you want to add React to an existing project, you can take a look at React's official guide for doing so. Alternatively, if you are creating a new React application, you can use one of the recommended toolchains to get the best user and developer experience.

Create React App is a convenient environment for learning React, and it is the recommended way to create A single-page application is an app that works inside a browser and does not require page reloading during use.single-page applications with React.

The official website also has advanced guides if you want to understand how React works behind the scenes.

Resources

As React is a fairly popular library, you can find a lot of comprehensive resources online. Here are some resources that can be useful:

  • The React Handbook - This article provides a well-rounded overview of React.
  • A list of officially recommended courses (some of which are free) - You can learn React from one of these resources if you prefer third-party books or video tutorials.
  • The React Blog - Updates about React's latest features will be available here.
  • React's API Reference - You can learn more about React's API here.
  • The React DevTools browser extension - This is used for inspecting and debugging React applications from within your browser's developer tools.

If you need help with React, you can get support from React's community of millions of developers that are active on Stack Overflow and discussion forums like Dev and Hashnode.

Lastly, if you want to know what to learn after getting familiar with React, here is a comprehensive roadmap that you can follow to become a full-fledged React developer.