(Since there is not much documentation for The release of Act18 yet, many of the concepts and content are cobbled together from multiple sources and contain my own personal understanding. There will probably be some errors by the time act18 is released, so writing this article is just a curiosity. So if you come across this article at some point in the future, remember to read it and focus on it.)

In fact, React18@alpha has been released for a while, because I was recently assigned a survey on how UMI supports react@18 Alpha. (Otherwise, I would have continued to squat.)

So I started to read the relevant documents and news.

The good news is that you can upgrade to Act18 very smoothly.

In UMI, for example, it only needs to change one line of code to support, regardless of testing and compatibility code.

- import { hydrate, render } from 'react-dom';
+ import ReactDOM, { hydrate, render } from 'react-dom';
- if (window.g_useSSR) {
- hydrate(rootContainer, rootElement, callback);
- } else {
- render(rootContainer, rootElement, callback);
-}

+ reactRoot = (ReactDOM as any).createRoot(rootElement, {
+ hydrate: window.g_useSSR,
+});

+ reactRoot.render(rootContainer);
Copy the code

And after changing from the business side, the page code does not need to do any modification of the project can run normally. You can then selectively add new features of Act18 to some of your new pages or optimize certain scenes.

React Native isn’t compatible with React Native.

Out of the box

When you simply change code like the one above, you’ll enjoy some of the features of Act18 straight out of the box.

  • Automatic batching to reduce rendering
  • Suspense SSR Support (New SSR architecture)

Automatic batching to reduce rendering

Batch processing allows React to group multiple state updates into a single re-render for better performance. This feature is available now in Act17, but batching will not be supported when interacting in different contexts. Now in Act18, automatic batching support for network requests, promises, setTimeout, and more has been added.

React17 – Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default.

function App() {
  const [count, setCount] = useState(0);
  const [flag, setFlag] = useState(false);

  function handleClick() {
    fetchSomething().then(() = > {
      // React 18 and later DOES batch these:
      setCount(c= > c + 1);
      setFlag(f= >! f);// React will only re-render once at the end (that's batching!)
    });
  }

  return (
    <div>
      <button onClick={handleClick}>Next</button>
      <h1 style={{ color: flag ? "blue" : "black}} ">{count}</h1>
    </div>
  );
}
Copy the code

Suspense SSR support

Suspense support wasn’t good at server rendering, but now you can use the new SSR architecture using the new API pipeToNodeWritable.

For example, we expect the final page to open like this :(green represents user interaction)

(Image from React18 Working Group DISCUSSIONS 37)

When you do not use THE SSR function, our pages will experience a short blank screen when the page is started. This is because at this time, the browser initiates js requests and loads, and the page will be executed and rendered after the JS files are downloaded.

When using SSR, React renders the component to Html on the server and sends it to the user, who is then presented with the basic framework of the page and can only do some built-in Web interactions (such as linking and form entry).

(Here, gray indicates that these parts of the screen are not yet fully interactive.)

The browser then loads the JS file as usual, and when the JS file is loaded, the current HTML is rendered interactive through the hydration process.

The technical name for this process is “Hydrate”, which translates as “activation” in VUE, and the React community prefers to describe the process as “hydration” or “water injection”, which is the equivalent of injecting “water” into “dry” Html.

There is also the same problem as not using SSR, page research is not interactive until the JS is fully loaded and the page components are fully “hydrated”. Act18 allows some pages to load data first and perform hydration first. Your page might look something like this.

Concurrent rendering (CONCURRENT rendering)

Of course, you can also selectively use some of the new features in Act18, which adds a major optional mechanic called concurrent rendering, which is the basis for many of the new features. It is worth noting that “concurrency” here still uses a single thread. But the single thread can be interrupted. Rendering can therefore be staggered between multiple rendering tasks, such as user interaction, network requests, timers, animations, and browser layout/drawing. The main distribution of its work is as follows:

The render task will be interrupted when it encounters a higher render task, and then the higher priority task will be executed first, and then the original render task will be returned after the task is completed.

You can use the new API to tell React which tasks are higher priority.

  • startTransition
  • useDeferredValue
  • SuspenseList

StartTransition Transitions are updated

This is a better understood API that wraps some setStates with startTransition and declares them to be less important rendering actions. Such as the search scenario mentioned in the official example.

When users enter in the search box, the search box needs to display the user’s input characters in real time, and then obtain new list data through network request (or local filtering data), and then update the list. There will be two setStates, one for the input value binding. One is the page data binding after the search.

import { startTransition } from 'react';


// Emergency: displays the input
setInputValue(input);

// Mark any internal status updates as transitions
startTransition(() = > {
  // Transition: Displays the result
  setSearchQuery(input);
});
Copy the code

If you need to perform some behavior while waiting for a transition rendering, such as loading operations, etc. You can use useTransition

import { useTransition } from 'react';


const [isPending , startTransition] = useTransition();
startTransition(() = > {
  // Transition: Displays the result
  setSearchQuery(input);
});

{ isPending  &&  < Spinner /> }
Copy the code

useDeferredValue

Delay updating less important parts of the screen (this has not been documented yet).

SuspenseList

Coordinate the order in which the load indicators appear (this has not been documented yet).

But from the use of Suspense, expectations are related to lazy load priorities, perhaps specifying which loads take precedence. (I guess, after all, that’s pretty much the concept of new documentation.)

// This component is dynamically loaded
const OtherComponent = React.lazy(() = > import('./OtherComponent'));

function MyComponent() {
  return (
    // Display the 
      
        component until OtherComponent is loaded
      
    <React.Suspense fallback={<Spinner />} ><div>
        <OtherComponent />
      </div>
    </React.Suspense>
  );
}
Copy the code

other

In addition to the features mentioned above related to collaborative multitasking, priority-based rendering, scheduling, and interrupts, there are other noteworthy features.

StrictMode StrictMode

Your components will be called load-unload multiple times to make sure they are in the correct state.

React intentionally double-invokes effects (mount -> unmount -> mount) for newly mounted components.

Note that this feature is enabled by default. React already uses this feature. — Fast Refresh, which preserves component state while developing, while editing provides immediate feedback.

Offscreen

The new Offscreen API allows React to maintain this state by hiding components rather than unloading them. To do this, React invokes the same lifecycle hooks as it did when uninstalling — but it also preserves the state of the React component and DOM elements. This is the Keepalive function in React.

This is one of the capabilities I was looking forward to, and is now implemented using

.

Of course, it can also be used as a pre-rendered page, rendering the user’s upcoming page in advance, similar to the Next Link page, will be pre-rendered.

Offscreen is the lowest in terms of priority and should theoretically be interrupted by any other rendering task.

It will not be in the initial 18.0 release, but may come in an 18.x minor.

Thanks for reading and feel free to comment if you have any questions. Like this article friends, please give a like, like my friends, you can pay attention to me. Thank you.

Refer to the link

Zh-hans.reactjs.org/blog/2021/0… Github.com/reactwg/rea… Github.com/reactwg/rea… Github.com/reactwg/rea… Github.com/reactwg/rea… Github.com/reactwg/rea… www.youtube.com/watch?v=bpV…