How React redefines front-end development

How React redefines front-end development

Original link: Yes, React is taking over front-end development. The question is why.

Author: Samer Buna

Translator: Yu Bolun

Please indicate the source.

<img src="https://pic4.zhimg.com/v2-4273d0f7dfc900d8e63856240d7d6bc7_b.png" data-rawwidth="1000" data-rawheight="364" class="origin_image zh-lightbox-thumb" width="1000" data-original="https://pic4.zhimg.com/v2-4273d0f7dfc900d8e63856240d7d6bc7_r.png">

TL;DR is too long to watch (Translator's Note)

  1. The main React core APIs are very few. Under the premise that you are familiar with new syntax such as ES6/7 and the Modern JavaScript technology stack, React is very fast to get started.
  2. React implements an abstract "virtual DOM" to represent the user interface, which means that as long as there is a suitable renderer to render, you can render the user interface written in React to any device or platform (Web/Native/VR)
  3. React uses a declarative approach to write user interfaces. You only need to "describe" to React what kind of interface you want, and then plan what state data changes the application will have, and how to update the remaining details and how to render React will automatically help You are done.
  4. Note: All frameworks or libraries will not be faster than native JavaScript. No matter how fast React is, you can t directly plug into the DOM, but the "virtual DOM" and "core Diff algorithm" implemented by React can only update the necessary parts of the interface, and It is not an overall replacement. This is an effect that is difficult for you to manually manipulate the DOM.


Here are a few reasons why React has become so popular:

  • It is difficult to use the DOM API. The virtual DOM implemented by React is more friendly to developers. It's like a proxy between the developer and the real browser.
  • React allows developers to describe their user interfaces in a declarative way and model the state of these interfaces. This means that developers only describe the interface in terms of the final state (such as a function), without considering the process and intermediate links. When some events trigger the application state change, React will automatically update the user interface according to the specific situation (imagine our interface is an animation, React allows us to divide the animation into fragments frame by frame, we only need to focus on one of them Fragments, and what changes are made to the fragments, as to how to change and the process, React can automatically handle it for us).
  • React is purely JavaScript, you only need to understand very few core APIs, plus a few simple functions to use. In addition, as long as your JavaScript skills are good enough, you can become a great React developer. The threshold for getting started is also relatively low. As long as you are familiar with JavaScript, you will be able to use React proficiently in just a few hours.

But there are more important reasons besides these appearances. Next, we will talk carefully. The first point is that it implements a virtual DOM (Virtual DOM) and core scheduling algorithm (the Reconciliation algorithm) . We can prove the value of these realizations through examples.

The official definition of React is that it is a library for building user interfaces. There are two more important parts of this:

1. First of all, React is a library, not a framework. It is not a complete solution. While using React, we also need to add other libraries to cooperate (unlike Angular). React only focuses on one thing and does it well.

2. The second part is what React focuses on: building the user interface. The user interface is the part that the user can see and interact with the program through it. Generalized user interfaces are everywhere, from buttons on microwave ovens to control panels on spaceships. And as long as the device supports JavaScript, we can use React to write the interface for it (recalling that the artificial intelligence of Hosts in "Western World" seems to be using React).

Browsers can run JavaScript, so we can come through natural React describe Web-based interface. I noticed here used description of the term, which is usually what we use React to do, we just tell React how to build specific user interface. If there is no React, we can only write it manually through raw Web APIs and JavaScript.

So when you hear the definition of "React is declarative", it actually means literally. We use React to describe the user interface (just tell what React is or how to do). The rest of React will do it for us, it will transform our declarative description into a user interface in the browser. These features of React are built on the basis of native HTML, but with React we can also describe dynamic data in addition to static content.

React has three main design concepts that have made it popular:

1-Reusable, nested, and stateful components

In React, we use components to describe the user interface. You can think of components as simple functions (regardless of any programming language). We call the function with some input and give us some output. We can reuse functions as needed, and build more complex functions from simple functions.

The role of the component is exactly the same; we call the input when the component is called "properties" and "state", and the output of the component is the description of the user interface (similar to the HTML of the browser). We can reuse a single component in multiple user interfaces, and components can nest other components.

However, unlike pure functions, a complete React component can have a private state state to save changing data.

2-The nature of responsive updates

The meaning of the word React itself (reaction) is a simple explanation of this concept. When the state of a component (input) changes, the user interface (output) it represents also changes. This change in the user interface description will also respond in the equipment we use.

In the browser, we need to regenerate the HTML view in the Document Object Model (DOM). With React, we don't need to worry about how to respond to these changes, or even manage when to apply changes to the browser; React will directly make changes to the state and automatically update the DOM when needed.

3-Virtualization of the view in memory

In React, we use JavaScript to write HTML. We rely on the function of JavaScript to generate the corresponding HTML through certain data, rather than extending the function of HTML. Extending HTML is an option for other JavaScript frameworks. For example, Angular extends HTML to use loops, conditions, and other functions.

When we receive data from the server (using Ajax in the background), we need more than HTML to process the data. Either use HTML with extended functionality, or use the capabilities of JavaScript itself to generate HTML. Both methods have their own advantages and disadvantages. React chose the latter approach.

In fact, this way there is a major advantage; use JavaScript to render HTML React able to save the HTML directly in the virtual memory representation (commonly referred to as virtual the DOM ). React uses virtual DOM to first render an HTML tree. Then, whenever the state data changes, we can update the tree structure data representing the DOM. Then React does not re-render the entire DOM, but only writes the new tree and the previous one. Difference (because React keeps two versions in memory for comparing differences). This process is called Tree Reconciliation, and I think it is the greatest invention in web development since Ajax!

In the following example, we will focus on the third concept, and you can see an example of a simple tree comparison process and the major changes it brings. We will write the same HTML example twice, first using native Web API and JavaScript, and then we will look at how to describe the same HTML tree using React.

To focus on this concept, we will not use components, we will use JavaScript timers to simulate changes in state data. We will not use JSX (using JSX in React can greatly improve the efficiency of our code writing). In this example, we directly use the React API to help everyone better understand the concept.

React's scheduling algorithm example

To try this example, you need a browser and a code editor. Actually you can also use online coding apps, But I will use a local file and test directly in the browser (no web server required):

We will write this example from scratch. Create a new directory and open it in your favorite editor:

mkdir react-demo
cd react-demo
atom .
 

Create an index.html file in this directory and write a standard HTML template in it. Include a script.js file in the template, and add a console.log statement to the script to test that our file is correctly imported:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React Demo</title>
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>
 

script.js

console.log('Included!')
 

Open the index.html file in your browser and make sure that you can see the empty template without problems. You can see the console.log test message you put in script.js in the console:

open index.html # Mac
explorer index.html # Windows
 

Now let us introduce the React library file, we can use its CDN directly, copy the script tags of react and react-dom and add it to index.html:

<script src="https://unpkg.com/react@latest/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
 

We need to introduce two React library files because the functions implemented by React are independent and can also be used on other platforms. In order to render the interface described by React in the DOM, you need to use the ReactDOM library:

Now we refresh the page and try to output React and ReactDOM in the console, and we should be able to see the global objects they expose:

With a simple configuration, we can now access the API of React and ReactDOM.

&amp;lt;img src="https://pic3.zhimg.com/v2-ccdde5f3df072652363bdd2c7ac1a66a_b.png" data-rawwidth="752" data-rawheight="349" class="origin_image zh-lightbox-thumb" width="752" data-original="https://pic3.zhimg.com/v2-ccdde5f3df072652363bdd2c7ac1a66a_r.png"&amp;gt;

To dynamically insert HTML in the page, we need to declare a DOM tag as a container:

<div id="js"></div>
 

Then write code in our script.js script file to get this container:

//  ES6   const  
const jsContainer = document.getElementById("js");
 

If we want to simply insert HTML fragments, we only need to use the native innerHTML method:

//  ES6  
jsContainer.innerHTML = `
  <div class="demo">
    Hello JS
  </div>
`;
 

If everything is working properly, you should see a "Hello JS" on the page.

In order to explain our concept more concisely, the code is kept as simple as this. Note that all the methods we use are native JS methods. Next, when we use React, we need to call the React API, and then React to interact with the DOM native API (in fact, the innerHTML method is used when the React source code finally inserts the DOM).

React's role is like an agent between us and the browser. We only need to tell React what to do, and React will deal with the browser itself. The only situation where we need to directly use native JS may only be the operation of obtaining the DOM container.

Next, let's use React to implement the example just now. It's still the same. Create a new page container with an id of react:

<div id="react"></div>
 

Similarly, get this container in our script.js script file:

const reactContainer = document.getElementById("react");
 

Next we need to use the render method in the ReactDOM library:

ReactDOM.render(
 /* TODO: React's version of the HTML template */,
  reactContainer
)
 

What we need to do next is a crucial point for you to understand React. Remember what we mentioned earlier, React uses JavaScript to write HTML.

We can generate a simple HTML interface by calling React's API

Instead of manipulating strings as before, in React, we define the content of the DOM by defining objects. The following method can generate the same content as the native JS example just now:

ReactDOM.render(
    React.createElement(
      "div",
      { className: "demo" },
      "Hello React"
    ),
    reactContainer
  );
 

The React.createElement method accepts many parameters:

  • The first is the tag name to generate HTML, such as div
  • Then there is the attribute of the label, but here we use the object to describe, for example {className: "demo"} will generate class="demo"
  • The third is the content contained in the label, such as the "Hello React" string in our example

We can now add a little bit of style, check it in the browser:

<style media="screen">
  .demo {
    border: 1px solid #ccc;
    margin: 1em;
    padding: 1em;
  }
</style>
 
&amp;lt;img src="https://pic2.zhimg.com/v2-42f52cd6d8d8bcb5c6819056246bd13d_b.png" data-rawwidth="525" data-rawheight="245" class="origin_image zh-lightbox-thumb" width="525" data-original="https://pic2.zhimg.com/v2-42f52cd6d8d8bcb5c6819056246bd13d_r.png"&amp;gt;

Now we have two nodes, one created by the native DOM Web API and the other created by the React API. The main difference is that the native method uses a string to represent the content of a node, while React uses a method to pass in an object to represent the content.

No matter how complex our interface is, when using React, all page elements are represented by objects passed in through the React.createElement method.

Next, let's try to add some other content. Let's try the HTML content of the nested structure. The native JS is still the same, represented by a string:

jsContainer.innerHTML = `
  <div class="demo">
    Hello JS
    <input/>
  </div>
`;
 

Using React is also very simple, we only need to modify the third parameter of the React.createElement method:

ReactDOM.render(
  React.createElement(
    "div",
    { className: "demo" },
    "Hello React",
    React.createElement("input")
  ),
  reactContainer
);
 

Seeing this step, you may be puzzled. Does using React complicate simple problems? It looks like this on the surface, but we have a reason to do so, please read on:

Let's add another label that shows the timestamp:

jsContainer.innerHTML = `
  <div class="demo">
    Hello JS
    <input/>
    <p>${new Date()}</p>
  </div>
`;
 

When using React, we need to pass in 5 parameters to indicate:

ReactDOM.render(
  React.createElement(
    "div",
    { className: "demo" },
    "Hello React",
    React.createElement("input"),
    React.createElement(
      "p",
      null,
      new Date().toString()
    )
  ),
  reactContainer
);
 

Now native JS and React still display the same content on the page.

&amp;lt;img src="https://pic1.zhimg.com/v2-62ca25207fdb9825413778ca3ff8bb80_b.png" data-rawwidth="528" data-rawheight="345" class="origin_image zh-lightbox-thumb" width="528" data-original="https://pic1.zhimg.com/v2-62ca25207fdb9825413778ca3ff8bb80_r.png"&amp;gt;

Judging from the current example, using React seems to be much more complicated and difficult than the native method. So what is the value of React that allows us to give up writing native HTML and use its API methods to write it? The key is not to generate the page for the first time, but how to update the content of the page afterwards.

Next, let's demonstrate with an example, let the timestamp change with every second.

The most straightforward method is to execute the defined method every second through the setInterval function:

const jsContainer = document.getElementById("js");
const reactContainer = document.getElementById("react");
const render = () => {
  jsContainer.innerHTML = `
    <div class="demo">
      Hello JS
      <input/>
      <p>${new Date()}</p>
    </div>
  `;
  ReactDOM.render(
    React.createElement(
      "div",
      { className: "demo" },
      "Hello React ",
      React.createElement("input"),
      React.createElement(
        "p",
        null,
        new Date().toString()
      )
    ),
    reactContainer
  );
}
setInterval(render, 1000);
 

Run our code. Now the timers in both nodes should work automatically. However, if you try the native JS node now, you will find that input cannot be entered, because every second, the DOM elements of this node are rebuilt. And you will find that the input box of the Rect node can be used normally.

Although React also repeatedly calls the render method, in fact, React will only re-render the part of the timer number that changes, and other content will remain unchanged, and the input box can naturally be used normally.

In the console, you can observe the similarities and differences between the two nodes in detail. All the content of the native node has been re-rendered, while React only updates the counter node.

&amp;lt;img src="https://pic3.zhimg.com/v2-366ef3ed2edad75788e063f038fdb2da_b.gif" data-rawwidth="669" data-rawheight="361" data-thumbnail="https://pic3 .zhimg.com/v2-366ef3ed2edad75788e063f038fdb2da_b.jpg" class="origin_image zh-lightbox-thumb" width="669" data-original="https://pic3.zhimg.com/v2-366ef3ed2edad75788e063f038fdb2da_r.gif"&amp ;gt;

React has an intelligent differential diff algorithm, through which we can generate only the part of the DOM node that needs to be re-rendered. This algorithm works because React's virtual DOM technology stores the structure and content of the DOM in JS.

Using virtual DOM, React keeps the last DOM version in memory. When it has a new DOM version generated to the browser, the new DOM version will also be saved in memory, so React can calculate the new version and the old version The difference between (in our case, the difference is the timestamp paragraph).

Then React will instruct the browser to update only the calculated difference, not the entire DOM node. No matter how many times we regenerate our interface, React will only add new "partial" updates to the browser.

This method not only improves efficiency, but also eliminates a lot of complexity in order to update the user interface. Having React to do all the calculations about whether we should update the DOM allows us to focus on the way we think about our data (state) and describe the user interface.

Then, we manage our data updates as needed, without worrying about the steps required to reflect these updates in the browser in the actual user interface (because we know React will do this automatically and in the most efficient way)!