Explain the new features of React 18 with cases - concurrent rendering, automatic batch processing, etc.

⭐️ This article was first published from Front-end Shura Field (click to join) , yes 一个由 资深开发者 独立运行 的专业技术社区, I am focused Web 技术、Web3、区块链、答疑解惑、面试辅导以及职业发展. The "Front-end Interview Review Notes" (click to subscribe) created by the blogger has been widely praised and has helped many students to improve their strength and get offers. Subscribe now and chat with bloggers privately to get a free mock interview/resume guidance service to help you evaluate the mastery of knowledge points and get more comprehensive study guidance!

React 18 will be released in March 2022. This release focuses on performance improvements and rendering engine updates. Meanwhile, React 18 laid the foundation for concurrent rendering, upon which future React features will be built.

In this article, I'll give a brief introduction to React 18 and explain several key concepts transitionssuch as .

React 18 features overview

category Function
concept Concurrency
characteristic Automatic batching, transitions, etc.
APIs createRoot, hydrateRoot, renderToPipeableStream, renderToReadableStream
Hooks useId, useTransition, useDeferredValue, useSyncExternalStore, useInsertionEffect
renew strict mode
abandoned ReactDOM.render, renderToString

Below, I will explain the above functions and features in more detail. First, let's upgrade to React 18

Upgrade to React 18

First execute the following command:

npm install react react-dom

Then, index.jsin , ReactDOM.renderchange to ReactDOM.createRootto create a rootnode, and use the rootnode to render the application.

Here's what it looks like in React 17:

import ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

ReactDOM.render(<App />, container);

After the update, this is what it looks like in React 18:

import ReactDOM from 'react-dom';
import App from 'App';

const container = document.getElementById('app');

// 创建 root
const root = ReactDOM.createRoot(container);

//渲染
root.render(<App />);

Concurrency

To understand concurrency, here is an example from the official:

Suppose we need to call two people - Alice and Bob. In a non-concurrent setup, we can only have one call at a time . We'll call Alice first, and then call Bob when we're done.

This is fine when the call time is short, but can be a problem if the call to Alice has a long wait time (eg waiting).

Please add image description

Whereas, in a concurrent setup, we can call Alice, and once we're on hold, we can call Bob .

That doesn't mean we're talking to two people at the same time. It just means we can have two or more concurrent calls at the same time and decide which call is more important .

Please add image description

Also, in React 18 with concurrent rendering, React can 中断、暂停、恢复或放弃渲染. This allows React to respond quickly to user interactions, even when it's doing heavy rendering tasks.

Before React 18, rendering was a single, uninterrupted, synchronous transaction that couldn't be interrupted once rendering started.

React 18 introduces the foundation of concurrent rendering , providing support for new features such as suspensestreaming service rendering and .transitions

What's new in React 18

automatic batch processing

React 18 has automatic batch processing. To understand batch processing, let's refer to an official store shopping example.

Say you're making pasta for dinner. But you find that you don't have the ingredients you need to make pasta, so you need to go to the store to buy them.

That's when you start cooking and find you're missing an ingredient, then you go to the store to buy the ingredient and come back to continue cooking. Come back only to find you need another ingredient, and then you go to the store to buy it...and come back. If this goes on, you may go crazy first.

In React, when you call setState, batching helps reduce the number of re-renders that occur when state changes . Previously, React batched state updates in event handlers like this:

const handleClick = () => {
    
    
setCounter();
setActive();
setValue();
}
// 最后重新渲染一次。

However, state updates that occur outside of event handlers are not batched . For example, if there is one Promiseor an api call is in progress, the state will not be updated in batches. like this:

fetch('/network').then( () => {
    
    
setCounter(); // 重新渲染 1 次
setActive();  // 重新渲染 2 次
setValue();   // 重新渲染 3 次
});
//一共重新渲染 3次

As you know, doing this is not a performant way. React 18 introduced automatic batching, which allows batching of all state updates , even in Promise、setTimeoutsand event callbacks. This significantly reduces the work that React has to do in the background. React will wait for a microtask to complete before re-rendering .

Automatic batching is available out of the box in React , but you can use it if you want to opt out flushSync.

Transitions

Transitions are a brand new one introduced in React 18 并发特性. It allows you to update markup as a transition, which tells React about them 可以被中断执行, and 避免回到已经可见内容的 Suspense 降级方案.

For example, when you're typing, two things happen: the cursor blinks as you type, and then the data is searched in the background.

If you feel it is not urgent to present the searched data to the user, then you can mark this action as transitions. This way, React will know which updates take precedence. This makes it easier to boost rendering performance.

In use, in React, you can use startTransitionto mark updates as transition. Here's an example of a typeaheadcomponent using transitionsmarkup:

import {
    
     startTransition } from 'react';

// 紧急
setInputValue(input);

// 非紧急: 将内部的任何非紧急状态更新标记为 Transition
startTransition(() => {
    
    
  setSearchQuery(input);
});

How are transitions different from debounce or setTimeout?

  • Unlike setTimeout, startTransition executes immediately .
  • setTimeout has a guaranteed delay, while startTransition has a delay that depends on the speed of the device and other urgent rendering .
  • Unlike setTimeout, startTransition updates can be interrupted without freezing the page .
  • React can keep track of pending states for you when marked as startTransition .

Suspense SSR

Client-side rendering and server-side rendering

During a client-side rendered application, the page's HTML is loaded from the server, along with any JavaScript required to run the page.

However, if the JavaScript bundle is large, or the connection is slow, this process can take a long time.

In the client-side rendering flow, the user has to wait a long time for the page to become interactive.
To optimize the user experience and avoid the user sitting on a blank screen, we can use server rendering.

Server rendering is a technique that renders the HTML output of React components on the server and sends HTML from the server. This allows the user to see some UI when the JS bundle is loaded and before the application becomes interactive.

In the server rendering process, we can display meaningful data to the user faster by sending HTML from the server
Server rendering further enhances the user experience of loading pages and reduces interaction time.

Before React 18, this part was often the bottleneck of the application and increased the time it took to render the component.

A slow component can slow down an entire page . This is because server rendering is either all or nothing. You can't tell React to defer loading slow components, and you can't tell React to send HTML for other components.

React 18 adds support for on Suspensethe . With the help of suspense, you can wrap slow parts of your application in Suspensecomponents , telling React to lazy load slow components. This can also be used to specify what can be displayed on load 加载状态.

In React 18, one slow component doesn't have to slow down the rendering of the entire application. Using Suspense, 可以告诉 React 首先发送其他组件的 HTML 以及占位符的 HTML. Then, 当慢速组件准备好并获取其数据时,服务器渲染器将在同一流中弹出其 HTML.

Displaying images on the server can allow slow components to show a loading state while other components render fully
This way, the user can see the skeleton of the page early on, and gradually show more content as more HTML arrives.

All of this happens before any JS or React is loaded on the page, which significantly improves user experience and user-perceived latency.

strict mode

Strict mode in React 18 will 模拟安装、卸载和重新安装have components in previous state. This sets the stage for a future 可重用状态where React can immediately mount the previous screen by reinstalling the tree with the same component state before unmounting.

Strict mode will ensure that the component is resilient to the effects of multiple installs and uninstalls.

end

All in all, React 18 sets the stage for future releases and focuses on improving the user experience.

Guess you like

Origin blog.csdn.net/ImagineCode/article/details/126686453