React 18 Version: What’s New!

React 18 Version: What’s New!

React 18 Version has been announced, but what's new about it? Let's know here complete details about this new version of React.

React 17, which was introduced in late 2020, failed to bring lots of innovative features. Rather, it emphasized enhancing the basics plus laying the foundation for future updates. All these were done to enable smooth, gradual adoption of what is going to come next.

This is how we get introduced to React 18. The plan for the subsequent version of React was announced by the React team recently, along with many upcoming features. Likewise, there was a publicly available alpha, release timeline, plus a Working Group committed to enhancing React 18.

Lots of things are happening with React at present, and therefore, let us take a look at all the declarations and some other details.

React 18 Working Group

Before diving into the remarkable new features, it is essential to talk about the React 18 WG (Working Group) since this type of concept has been used for the first time in the development of React.

The group’s objective is to offer feedback and make the broader ecosystem ready for the forthcoming release of React. Although it is restricted to selected members, it will be feasible for you to always check it out since the conversation is hosted through GitHub Discussions and made publicly available as well.

You will be able to come across different concepts, research findings, and feature overviews from the React team without any problem.

React 18 Working Group happens to be the first such attempt for involving the ecosystem and community builders more in the creative procedure behind the subsequent release of React.

How is it going to influence the result? We need to wait and watch.

React 18: Innovative Features

As compared to the earlier version, it seems that React 18 is packed with innovative features. While some are remarkable enhancements, others shine new light on the concurrent model of React. In any case, there is plenty to unpack, with many more coming down the road!

Automatic Batching

There are massive enhancements to automatic batching when it comes to performance.

Before the introduction of React 18, multiple state updates were already batched by React into one for reducing unwanted re-renders. Nevertheless, it took place in DOM event handlers only, and therefore, timeouts, Promises, or other handlers did not use it to their advantage.

const App = () => {

const [firstCount, setFirstCount] = useState(0);

const [secondCount, setSecondCount] = useState(0);

const handleClick = () => {

setFirstCount((count) => count + 1); // No re-render yet

setSecondCount((count) => count + 0.5); // No re-render yet

// Re-render (updates batched)

};

/*

const alternativeHandleClick = () => {

Promise.resolve().then(() => {

  setFirstCount((count) => count + 1); // Re-render

  setSecondCount((count) => count + 0.5); // Re-render

});

};

*/

return (

<div>

  <button onClick={handleClick}>Next</button>

  <span

    style={{

      color: firstCount % 2 === 0 ? "blue" : "black",

    }}

  >

    {secondCount}

  </span>

</div>

);

};

With the introduction of version 18, React will batch state updates irrespective of where they take place, so long as it is risk-free to do. This leads to superior performance without any extra involvement.

Strict Mode Changes

Next, we will mention several additions to the Strict Mode, which includes new behavior named “strict effects.” This will be double-invoking effects, particularly mount as well as unmounts ones.

The extra checks are here for testing against several mount/unmounts cycles. Apart from ensuring more resilient components, it likewise corrects behavior at the time of development with Fast Refresh (when components are mounted or unmounted) plus an innovative “Offscreen API,” which is presently in the works.

Better performance will be enabled by Offscreen API by concealing components rather than unmounting them, maintaining the state, and still calling the effects of mount/unmount. This will play an important role in optimizing components such as virtualized lists, tabs, and so on.

Root API

The render function, which was available at the beginning of every React app, will be swapped by createRoot.

This new API happens to be the gateway for accessing new features of React 18. Moreover, it is provided together with legacy API for encouraging gradual adoption and ease-out prospective performance comparisons.

New root API is likewise somewhat different syntax-wise.

import ReactDOM from "react-dom";

import App from "App";

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

// Old

ReactDOM.render(, container);

// New

const root = ReactDOM.createRoot(container);

root.render();

It is evident to you how your React app’s root is now separate. Being a data structure pointer connected to a DOM element, the root had been opaque to the render function’s user previously.

It is imperative to create the root using the createRoot function and call the render method on it after this. Apart from enabling new features, it is likewise simpler and clearer to update when needed.

The new API likewise modifies the way hydrate functions and render callback work. The callback argument has been removed completely since it is difficult to time it properly. Rather, you ought to use, e.g., ref callback or timeout on the root.

// ...

// Old

ReactDOM.render(, container, () => console.log("renderered"));

// New

const App = ({ callback }) => {

return (

<div ref={callback}>

  <h1>Hello World</h1>

</div>

);

}

const root = ReactDOM.createRoot(container);

root.render(<App callback={() => console.log("renderered")} />);

As for hydrate, it transforms into a config option from a separate function, making it more sensible.

// ...

// Old

ReactDOM.hydrate(, container);

// New

const root = ReactDOM.createRoot(container, { hydrate: true });

root.render();

Concurrent Rendering

There is no doubt that the most significant update for React 18 is available with the “concurrent mode” or “concurrent rendering,” as it is now called.

The naming alteration is essential given that it helps the adoption of concurrent features to be enabled gradually. This will enable you to adopt concurrent features seamlessly without rewrites at your convenience.

New APIs

New APIs are available with new features. However, all of these happen to be opt-in and cover things such as Suspense updates, state transitions, plus new hooks when it comes to concurrent rendering.

startTransition

A new API has been introduced by React 18 for handling heavy state updates such as list filtering or data fetches. In such cases, setting the state simply will trigger updates immediately, probably slowing down the UI.

For combating this, you will come across an innovative API as startTransition function. It will be marking state updates as transitions, making it non-urgent to handle them.

import { startTransition } from "react";

// ...

// Urgent -> show updated input

setInputValue(input);

// Transition (non-urgent) -> show search

startTransition(() => {

setSearchQuery(input);

});

startTransition will come of use when you want to keep native user input snappy as you perform non-urgent and complicated operations in the background. If the user updates the search query, that will be reflected by the input field instantly, while the earlier transaction will be canceled.

Besides startTransition, an innovative useTransition will offer info regarding whether or not the given transition is pending. It will also enable you to set an extra timeout as well.

// ...

const App = () => {

// ...

const [isPending, startTransition] = useTransition({ timeoutMs: 2000 });

startTransition(() => {

setSearchQuery(input);

});

// ...

return (

<span>

  {isPending ? " Loading..." : null}

  {/* ... */}

</span>

);

};

// ...

This information can be used by you for render loading UIs, implementing custom handling, and so forth.

useDeferredValue

The innovative useDeferredValue hook is available to us while continuing the trend of accepting value changes.

import { useDeferredValue } from "react";

// ...

const [text, setText] = useState("text");

const deferredText = useDeferredValue(text, { timeoutMs: 2000 });

// ...

A deferred version of the accepted value will be returned by the hook that will “lag” the original one. Although it is similar, it is somewhat different from the already mentioned transitions. Nevertheless, it is useful when you have to implement complicated state-based deferred behaviors.

SuspenseList

Ultimately, you will come across the new component, which helps to organize the order in which the directly-nested and components become revealed. In addition, this component handles cases where fetched data can arrive in random order. Because of , it is possible to keep it orchestrated while keeping the UI in check.

import { Suspense, SuspenseList } from "react";

const App = () => {

return (

<SuspenseList revealOrder="forwards">

  <Suspense fallback={"Loading..."}>

    <ProfilePicture id={1} />

  </Suspense>

  <Suspense fallback={"Loading..."}>

    <ProfilePicture id={2} />

  </Suspense>

  <Suspense fallback={"Loading..."}>

    <ProfilePicture id={3} />

  </Suspense>

</SuspenseList>

);

};

// ...

You will find more information, such as adjusting behavior with its props in the WIP (Work-In-Progress) documentation.

Suspense Improvements

In combination with and other concurrent rendering updates, several enhancements have been made to the general Suspense behavior.

The most significant advancement of Suspense is turning out to be a stable feature finally with massive architectural alterations under the hood along with an innovative name – “Concurrent Suspense.” Nevertheless, the terminology is used mostly for differentiating the feature versions when it comes to migration since the user-facing modifications are minimal.

The most noteworthy user-facing change is needed to render the suspended siblings of the component.

// ...

const App = () => {

return (

<Suspense fallback={<Loading />}>

  <SuspendedComponent />

  <Sibling />

</Suspense>

);

};

// ...

The above code, in React 17, both lead to being mounted instantaneously plus its effects called, only to be concealed soon after.

This has been fixed by React 18 by not mounting the component whatsoever and first waiting for to be resolved. Although this helps fix some problems regarding libraries in React ecosystem, you should not observe that much.

Let's know more here new features of React 18: https://www.rlogical.com/blog/react-18-version-whats-new/

react react-native javascript api

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

React Native App Developers India, React Native App Development Company

Hire React Native app developers India from a preferred React Native app development company by innovative industry leaders. Let's Discuss Your Project.

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...

Factors affecting the cost of hiring a React Native developer in USA - TopDevelopers.co

Want to develop app using React Native? Here are the tips that will help to reduce the cost of react native app development for you.

How much does it cost to develop a React Native mobile app?

Save time & money when choosing AppClues for React Native Mobile app Development. We build React Native apps for Android & iOS using the same code & provide optimal output.