Technology Blog

Look deep into latest news and innovations happening in the Tech industry with our highly informational blog.

What is new in React 18

hkis

React 17 was focused on improving the fundamentals but there are few important things that got added in React 18. The React Team revealed new features that would be coming to React in React 18 and in this blog, we will explore these features and how they can help you in the near future!

Strict Mode

Strict Mode has a few additions such as a new behaviour called “strict effects”. This allows us to double-invoke effects like mount and unmount. It creates an environment to correct behaviour with Fast Refresh during development, not only looking for more resilient components. There is also an ‘offscreen API’ which is currently being built.

An offscreen API will enable better performance by hiding components instead of unmounting them, keeping the state, and still calling the mount/unmount effects.

Automatic Batching

There is now major improvements with automatic batching. We will first look at performance.

React already batched, in other words grouped, multiple state updates into one to minimise unnecessary re-renders. However, elements like Promises, timeouts, or other handlers didn’t take advantage of it as it was only limited to DOM event handlers.

This all changes with React 18 which will batch state updates without limits, as long as it’s safe to do. The result, you ask?…This would create better performance without any additional involvement.

There are huge improvements to automatic batching. In the earlier versions of React, it uses to batch multiple state updates into one to reduce unnecessary re-renders. The problem was it was done only in DOM event handlers and not in promises, timeouts, or other handlers.

Let’s look at the below code on how batching occurs with earlier versions of React.

export default function App() {
    const [count, setCount] = useState(0);
    const [color, setColor] = useState(undefined);
    
    const handleClick = () => {
        setCount(count + 1); //No re-render
        setColor(count % 2 === 0 ? "Green" : "Red"); //No re-render
        // Now re-renders once at the end (this is batching)
    } 
    return (
        <>
            <button onClick={handleClick}>Next</button>
            <span style={{
                color: count % 2 === 0 ? "red" : "green",
            }}>
                {color}
            </span>
        </>
    );
}

With React 18, promises, timeouts, or other handlers will also take advantage of that. It will batch state updates no matter where they happen. This will result in better performance.

Let’s look at the below code where batching occurs. In the below code batching works fine with React 18 but earlier versions of React will not batch it.

export default function App() {
    const [count, setCount] = useState(0);
    const [color, setColor] = useState(undefined);    const handleClick = () => {
        Promise.resolve().then(() => {
            setCount(count + 1); //Re-render
            setColor(count % 2 === 0 ? "Green" : "Red"); //Re-render
        });
    }    return (
        <>
            <button onClick={handleClick}>Next</button>
            <span style={{
                color: count % 2 === 0 ? "red" : "green",
            }}>
                {color}
            </span>
        </>
    );
}

However, if there is a need where we don’t want our component to be batched, we can opt-out that component using ReactDOM.flushSync().

Concurrent Rendering

Concurrent rendering is definitely one to look for as it is by far the biggest update with React 18.

Prior to this name, it was called ‘concurrent mode’. The change in name signifies the enabling of gradual adoption of concurrent features. This allows us to adopt concurrent features without rewriting code and do so at your own pace.

New APIs

With React 18, we get several new APIs which come in many forms.

startTransition

Its purpose is to spot state updates as transitions, making handling them non-urgent.

useDeferredValue

This hook will give you a deferred element of the passed value, which will follow the original one, up to provided timeout.

The ‘useDeferredValue’ is a hook that will return a deferred version of the passed value. It takes in the state value and a timeout in milliseconds. It will return a deferred version of the value that may “lag behind” it for most timeouts.

import { useDeferredValue } from "react";
const [text, setText] = useState("react js");
const deferredText = useDeferredValue(text, { timeoutMs: 2000 });

This is commonly used to keep the UI responsive when we have something that renders immediately based on user input and something that needs to wait for a data fetch.

Suspense

In the previous version of react, the below code would result in ReadyComponent being immediately mounted and its effects called. Like its name, Suspense suspends something until it’s ready to be rendered.

<Suspense fallback={<Loading />}>
    <ComponentWaitingForData />
    <ReadyComponent />
</Suspense>

This has been taken care of in React 18.

Referring to the above code, Now it won’t mount the ReadyComponent, instead will waiting for ComponentWaitingForData to resolve first.

SuspenseList

A SuspenseList excepts a two prop. ‘revealOrder’ and ‘tail’.

‘revealOrder’ is one of SuspenseList configuration options. It can be undefined, together, forwards, and backwards.

  • undefined (default): reveal children as suspenders resolve.
  • together: reveal children together, once all suspenders are resolved.
  • forwards: render children from top to bottom, indifferent to suspender. resolution order
  • backwards: render children from bottom to top, indifferent to suspender resolution order

‘tail’ props dictates how the unloaded items in a SuspenseList are shown. Its value can either be collapsed or hidden.

<SuspenseList revealOrder="forwards" >
    <Suspense fallback={<p>Loading attendance...</p>}>
        <Attendance id={facultyID}/>
    </Suspense>
    <Suspense fallback={<p>Loading homework...</p>}>
        <Homework id={facultyID}/>
    </Suspense>
</SuspenseList>

The above code with SuspenseList demonstrates that we can set the revealOrder to force the attendance to appear first and then the homework section.

<SuspenseList revealOrder="forwards" tail="collapsed">
    <Suspense fallback={<p>Loading attendance...</p>}>
        <Attendance id={facultyID}/>
    </Suspense>
    <Suspense fallback={<p>Loading homework...</p>}>
        <Homework id={facultyID}/>
    </Suspense>
</SuspenseList>

The above code demonstrates that only one fallback is shown at a time. i.e first the fallback for the attendance and then the fallback for the homework.

Root API

createRoot will replace the render function. The new API is the gateway to accessing new React 18 features. It’s meant to encourage gradual adoption and ease-out potential performance comparisons.

For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using React JS, please visit our technology page.

Content Source:

  1. medium.com
  2. javascript.plainenglish.io