Last Updated:

What is React?

React is a declarative JavaScript library for creating user interfaces. It allows you to assemble a complex UI from small, isolated pieces of code called "components."

React provides two syntaxes for creating components: class and functional. Class is rarely used because class syntax is often redundant to describe components. Therefore, in the article we will consider the functional components.

The functional component in React is a JavaScript function that receives an object with data for rendering the component as input - they are called props, and at the output returns a description of the interface that you want to display.

An example with a user greeting on React might look like this:

import React from "react";

function HelloWorld(props) {
   return (<h1>Hello World!!! My name is <b>{props.name}</b></h1>);
}

export default HelloWorld;

This code is easy to understand, even if you don't know the syntax of React. Here, as a function, the React component is described As input, it receives an object with data, props, which contains a property with the user's name. The function returns special code that looks like HTML markup. We will tell you more about it later, but for now it is only important to understand that this code works. React will actually display a DOM tree on the page - it will correspond to the markup that it returned But unlike regular HTML, we were able to substitute data from the props object into the markup, thereby templateting it.

HelloWorld.nameHelloWorld.<b>{props.name}</b>

React code looks lighter and more concise than a pure JS solution. We don't describe how to redraw the interface. Instead, we specify what we want to display in place of the component, and we use HTML-like syntax to do so. This approach makes it relatively easy to solve more complex problems. For example, to redraw the layout of the cart page and display the interface of the order page in its place.

React uses the Virtual DOM for its redraws. This allows you to update only the changed nodes of the DOM tree, rather than redrawing the entire page. Thanks to this, applications do not consume unnecessary resources.

React solves the problems of front-enders in the development of interfaces of dynamic sites and SPA-applications. When using the classic bundle of JavaScript and HTML, redrawing the interface is very complicated. React does not limit the developer's capabilities, unlike any frameworks.

Is React in demand in the front-end development market? Comparison with Angular and Vue

Projects in pure JavaScript have become exotic - more often developers use reactive libraries and frameworks: React, Vue or Angular. It is difficult to understand which framework is better and more convenient – developers are constantly arguing and cannot come to a compromise.

In our opinion, modern libraries and frameworks are similar to each other – each of them has its advantages and disadvantages, but in general they are equally effective. Articles about comparing tools are often biased, as developers rely on personal preferences. For example, if a team spent a year rewriting a site from Vue to React, its members would say that React is better, and vice versa. Therefore, you should not waste time comparing different reactive frameworks and libraries. Instead, it is better to study at least one of them.

And yet React has one advantage – React developers are hired more often. Here is a comparison of the number of vacancies for React, Angular and Vue on the hh.ru:

Number of vacancies for front-endenders with 1-3 years of experience

Companies are looking for React developers twice as often as developers on Vue or Angular.

If we compare the number of downloads of npm packages, then here React surpasses frameworks. According to npm trends over the past year, the average monthly number of downloads of the React package is 11 million, Angular and Vue is about 2.8 million.

React package

Although formally they cannot be compared at all, since React is a library, and Vue and Angular are frameworks. However, due to various transitional variations, such as the "progressive framework", and other features, there are almost no differences between libraries and frameworks in the frontend.

Typical Tasks of a React Developer

Typical tasks of a developer are to write React components. Further, the pages of the site are built from such components.

Reactive frameworks are data-driven programming, so it's important to know the type of data that comes into the components. Because JavaScript does not explicitly describe data types, React developers typically use TypeScript in their projects.

React is only responsible for displaying the interface. Therefore, around it there is a whole ecosystem of tools that solve the rest of the tasks of front-end development:

State management – Libraries for working with global application data that are not specific to a specific component, but are needed in many parts of the site. Among the popular tools for wealth management are Redux and Mobx.

Routing. SPA implies the transition between the pages of the site without additional requests to the server. Therefore, the tasks of routing, the correspondence of pages to certain URLs, are also handled by front-enders. For such tasks, there are a number of popular libraries, in particular, React Router.

Server-side rendering. One of the problems with SPA is that many search engines expect HTML rather than JavaScript. Therefore, it is important to give to the requests of search engines not an empty HTML file on which JavaScript "draws" the interface, but ready-made HTML markup. To generate it from components, the Next.js framework has been developed.

Create UI elements. Typical UI elements are usually not written from scratch - ready-made UI libraries are used for them: MUI, Ant Design and many others.

Styling. For styling in React, they often use not the usual CSS, but the CSS-in-JS approach. It allows you to describe styles directly in JavaScript. One of the most popular implementations of the CSS-in-JS approach is the styled-components library.

This is not a complete list of tasks and tools that a React developer works with in everyday life.

How to work with React components?

Let's take a closer look at the syntax of the components. As we have already said, a React component is a JavaScript function that receives an object with data to render the component as input, and returns a React element as output.

A React element is a JavaScript object that describes a DOM tree node. It has a special format that React can handle and display on the page. To create such objects, the React library provides the .

React.createElement

To create markup on the page, you can write a React component:

<p>Hard to read <b>React.createElement</b>!!!</p>
import React from "react";

function HelloReact() {
   // no need to think what it is, we will use JSX next
   return React.createElement(
     "p",
     {},
     "Hard to read"
     React.createElement("b", {}, "React.createElement"),
     "!!!"
   );
}

The calls don't look intuitive. Looking at the code, it is difficult to understand what will be displayed on the page. Therefore, it is usually not directly applied, but uses a special JSX syntax.

React.createElementReact.createElement

What is JSX?

JSX is a JavaScript extension for describing an interface directly in JS using syntax similar to HTML. Using JSX, the example would look like this:

import React from "react";

function HelloReact() {
   return <p>Hard to read <b>React.createElement</b>!!!</p>
}

With JSX, the code became clearer. You can immediately see which fragment of the DOM tree the component describes.

JSX allows you to template markup by substituting data calculated from JavaScript expressions into it. To do this, use curly brace syntax. If you rewrite the example from the beginning of the article in React, it may look like this:

import React from "react";

function HelloWorld(props) {
   return (<h1>Hello World!!! My name is <b>{props.name}</b></h1>);
}

export default HelloWorld;

Here, the component receives the user name in the object and returns the desired markup based on this data: . With curly brace syntax, the value from the variable is substituted into JSX. 

 

However, the browser knows nothing about JSX and does not know how to interpret it. When using JSX, you need to configure the project assembly so that JSX automatically transforms into JavaScript objects and a pure JS enters the browser. To do this, there are Babel plugins and presets, as well as projects like CreateReactApp. In this article, we use the codeSandbox online IDE, which provides a ready-made template for React projects.

Now let's see how to get React to display JSX markup. To do this, React provides the . The first parameter is passed to it JSX-markup. The second is the node of the DOM tree, in which you need to insert a piece of the interface.ReactDOM.render

To output a component to a DOM node with an id, you need to write:HelloWorldroot

import ReactDOM from "react-dom";
import HelloWorld from "./hello-world";


const rootElement = document.getElementById("root");
ReactDOM.render(HelloWorld({name:"Вася"}) , rootElement);

A call with an object will return the desired JSX markup, and store a reference to the DOM element with an id . As a result, the call will insert the interface received from the component into the desired DOM node. 

HelloWorld

{name:"Vasya"}

rootElementrootReactDOM.render(HelloWorld({name:"Vasya"}) , rootElement)

Manually, as functions, components usually do not call. The fact is that in JSX you can insert components as ordinary HTML tags, passing data through attributes. When you render a component in place, JSX displays the markup that the component returns.

The name of a component in JSX must begin with a capital letter, otherwise JSX will identify it as a regular HTML tag.

Thus, instead of writing: .

ReactDOM.render(HelloWorld({name:"Bob"}) , rootElement);ReactDOM.render(<HelloWorld name="Bob" /> , rootElement);

Composition of components and hooks

 

The ability to insert not only HTML tags into JSX, but also its components is one of the most important techniques in React. Website pages are usually much more complex than an example: they consist of hundreds or even thousands of HTML elements. Describing such a page in a single module or component is a bad idea. The code will turn into a huge sheet. Therefore, the pages are divided into smaller pieces of the interface, and each of them is implemented as a separate component. This technique in React is called component compositionHello World

The same example c can be represented as a composition of two small components:HelloWorld

// Name component
import React from "react";

function Name(props) {
   return <b>{props.name}</b>;
}

export defaultName;

// HelloWorld component
import React from "react";
import Name from "./name";

function HelloWorld(props) {
   return (
     <h1>
       Hello World!!! My name is <Name name={props.name} />
     </h1>
   );
}

export default HelloWorld;

Now the user name rendering component is responsible It can be used not only in , but also in any other part of the interface where you need to display the user name. Name.HelloWorld

For more complex pages, the composition may be larger, for example:

Thus, the interface in React is a tree of components, each of which is responsible for its own piece of the interface. Since data is only transmitted through props from top to bottom, from parent components to child components, this forms a unidirectional data stream. Working with them becomes more predictable and understandable.

The user interfaces created with React are not static. We can redraw them in response to the user's actions. To do this, React provides React hooks.

Hooks are functions that allow you to change the standard behavior of the system with your own code. However, the feature interface limits these changes to system-safe limits.

In the case of React, hooks help to manage the life cycle of the component, allowing you to call, for example, its redrawing at the right time.

As a result, the React counter may look like this:

import React, { useState } from "react";

export default function Counter({ initValue }) {
  const [value, setValue] = useState(initValue || 1);

  return (
    <div>
      <button type="button" onClick={() => setValue(value - 1)}>-</button>
      <span> {value} </span>
      <button type="button" onClick={() => setValue(value + 1)}>+</button>
    </div>
  );
}

useState is a special React hook for storing the state of the component. When the state changes, the component is redrawn.

When called, returns an array whose first element is a status value. The second element stores a setter function with which you can change the status value. For buttons, props are passed. It contains a function that is called when the button is pressed - with a new status value. This causes a redraw and the current value is displayed on the screen. useStateonClicksetValuevalue

useState is just one of the many hooks available. Moreover, if necessary, the developer can write his custom hooks.

So, what are the advantages of React in comparison with native JavaScript:

  1. React provides a declarative description of the interface— it is more convenient to work with than with a string of imperative DOM API statements.
  2. React decides which nodes of the DOM tree to update at what time. It doesn't perform unnecessary operations, so React code is faster than most naïve pure JavaScript implementations.
  3. React has excellent documentation. Self-written solutions for implementing data binding are usually poorly documented or not documented at all.
  4. Thanks to JSX, in one component, we see both the logic and the markup with which this logic should work. They are usually inextricably linked, and seeing them side by side is much more convenient than storing HTML and JavaScript separately.
  5. Splitting the code into components allows you to reuse the code.

Results

React is in demand in the world of modern front-end development: many developers use it by default to write interfaces. Such popularity has led to the fact that some Junes begin to learn React, not knowing the basic JavaScript. This is a gross error. React is just a JS library, and to master it, you need to know JavaScript well.

When learning React, spend more time on the functional syntax of writing components — it is used more often. On class components, as a rule, only "legacy" remains written. We also recommend that you master TypeScript, because it is used in most React projects.

React has its own philosophy, techniques and limitations that must be observed in order to write high-quality code. Therefore, it is important not only to learn the syntax, but also to communicate with more experienced colleagues, to show them your code. This is the only way you can become a good React developer.