Categories
Frontend

React 18 thoughts

// Before
import { render } from 'react-dom';
const container = document.getElementById('app');
render(<App tab="home" />, container);
// After
import { createRoot } from ‘react-dom/client’;
const container = document.getElementById(‘app’);
const root = createRoot(container);
root.render(<App tab=”home” />);

Concurrency, is the main feature.

The main reason that it’s using “createRoot”, is because the new behind-the-scenes mechanism that enable React to prepare multiple version of the UI components at the same time, which is CONCURRENCY. Prior to React 18, updates were handled with synchronous rendering, thus with single, uninterrupted transactions. NOW rendering is interruptible. The key is that react is now basically preparing the components without blocking any user input or app flow.

For example:

Autocomplete is always a good example. In React 18, we can ask the component to be managed in the background. While the transaction is pending, the user still is able to type without a laggy experience.

I knew in React 17 we can do debounce and throttle, the examples below are just for comparation.

Source: Examples for React 18 Concurrency

Automatic Batching

Automatic Batching or default grouping multiple state updates (versus previous versions which only grouped updates inside event handlers) into a single re-render. Before React 18, it’s only do batch state updates when it’s in the scenarios browser-like “click event”. If it’s wrapped in a call back and it won’t do “batch state updates”. NOW React 18 will batch updates automatically, no matter where the updates happen.

Source: Automatic Batching.

Transitions 

It allows for a new way to differentiate between updates. Just like the autocomplete example above, we ensure the UI updates will not block user typing behavior.

Official React: Transition Docs

Suspense

Suspense Features for declaring the loading state of the component tree, which work well when combined with a transition API.

A perfect example from YouTube below:

More Info: Suspense in React 18

New Client and Server Rendering APIs

It’s related to the new method createRoot to render (and unmount), but read more on React DOM Client and React DOM Server

New Strict mode: useEffect is Double Called

Other Stuffs