DEV Community

Cover image for React v18.0: A guide to its new features and updates | iFour Technolab
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

React v18.0: A guide to its new features and updates | iFour Technolab

Introduction

ReactJS is an open-source, component-based JavaScript front-end toolkit that allows you to develop a single-page application (SPAs). It is developed by Facebook in 2013. This library allows the reusing of UI components. The new version of React v18.0 was recently launched in March 2022 with new features like performance improvements, concurrency, automatic batching, new APIs like startTransition, and streaming server-side rendering with support of suspense.

Concurrency in React 18

In the context of React.js, concurrency means having more than one task in progress at a time, and concurrent tasks can overlap depending on which is more urgent & with more priority.

In all previous versions of React, it could handle only one task at a time, and a task could not be interrupted once it had started. This approach is called Blocking Rendering. To overcome this issue, React 18 introduced Concurrent Mode.

React 18 introduces concurrent rendering and new features such as streaming server rendering, and transitions are powered by concurrent rendering.

Automatic Batching

All previous versions of React batched multiple state updates only inside event handlers like onClick to avoid multiple re-renders.

React 18 adds automatic batching to improve performance. Now, in the new version of React branches updates the stated in React events handlers, setTimeOut, promises and native event handler, and so on.

React event handlers


<xmp>
import { useState } from "react";

function App() {
  const [counter, setCounter] = useState(0);
  const [text, setText] = useState("Before Update");

  const handleClick = () => {
    setCounter(1);
    setText("After Update");
  };

  return (
    <>
      <h2>{counter}</h2>
      <h3>{text}</h3>
      <button onClick={handleClick}>Change</button>
    </>
  );
}

export default App;


</xmp>

Enter fullscreen mode Exit fullscreen mode

After fetch call


<xmp>
  const handleClick = () => {
    fetch("YOUR_API_URL").then(()=>{
      setCounter(0);
      setText("After Update")
    })
  };



</xmp>

Enter fullscreen mode Exit fullscreen mode

In setTimeOut


<xmp>
const handleClick = () => {
    setTimeout(() => {
      setCounter(0);
      setText("After Update");
    }, 5000);
  };


</xmp>

Enter fullscreen mode Exit fullscreen mode

Native event handlers


<xmp>
 const el = document.getElementById("button");
  el.addEventListener("click", () => {
    setCounter(count + 1);
    setText("After Update");
  });

</xmp>

Enter fullscreen mode Exit fullscreen mode

Read More: A complete guide on React fundamentals: Props and State

StartTransition API

The StartTransition API was introduced in React 18. This API helps you to keep your App responsive without blocking your user interaction. React 18 allows you to mark specific updates as transitions.

We can divide the updates into two categories in React:

  • Urgent updates: display direct interactions like typing, clicking, etc.
  • Non-Urgent (Transition) updates: change UI views.

State updates that are wrapped inside StaratTransition API are considered non-urgent, so they can be suspended or interrupted by urgent updates.

For example, when a user typing in a search input field, two things would happen: a blinking cursor that shows the user is typing and search functionality running in the background that searches the data which is typed.

Here when the user is typing, blinking the cursor is an urgent update, and searching typed data is a non-urgent update.

These non-urgent updates are called transitions. By making non-urgent UI updates, React will know which updates to give more priority.


<xmp>
import { useTransition, useState } from "react";

export default MyApp = () => {
  const [text, setText] = useState("");

  const [pending, startTransition] = useTransition();

  const handleChange = (e) => {
    // urgent update
    setText(e.target.value);

    // non-urgent update
    startTransition(() => {
      setSearchQuery(e.target.value);
    });
  };

  return (
    <>
      {pending && <h1>Loading....</h1>}
      <input
        type="text"
        value={text}
        onChange={() => {
          handleChange(e);
        }}
      />
    </>
  );
};



</xmp>

Enter fullscreen mode Exit fullscreen mode

Here in the above example, we used the useTransition() hook. This hook returns a Boolean variable value pending which indicates whether the transition is active or inactive. Using pending we can show to the user loading page or loading component.

The useTransition() hook also returns a function startTransition .This function accepts a callback function in which you set the state. The state will not be set or updated immediately.


<xmp>
import { useState, startTransition } from "react";

export default MyApp = () => {
  const [text, setText] = useState("");

  const handleChange = (e) => {
    // urgent update
    setText(e.target.value);

    // non-urgent update
    startTransition(() => {
      setSearchQuery(e.target.value);
    });
  };

  return (
    <>
      <input
        type="text"
        value={text}
        onChange={() => {
          handleChange(e);
        }}
      />
    </>
  );
};

</xmp>

Enter fullscreen mode Exit fullscreen mode

Here in the above example, we directly imported startTransition from React. While we are using this second approach, this approach does not give Boolean variables like pending to check whether the transition is active or not.

Suspense on the server

In a client-rendered app, the browser loads the HTML of a page from the server. JavaScript also loads with HTML page to run the page and make it interactive.

If the size of the JavaScript bundle is huge or if the user has a slow connection, then the browser takes more time to load the content and become interactive.

If we use server rendering, then it optimizes the user experience and avoids having to sit on a blank screen.

In the Server rendering technique render the HTML output of React components on the server and send HTML from the server. So, the user can view some UI while JavaScript bundles are loading and before the app becomes interactive.

In React while server rendering one slow component can slow down the entire page. Because we couldn’t tell React to load first other HTML components which are not slow.

React 18 has a new feature Suspense on the server. When we use suspense, we can wrap a slow part of our app within the suspense component, so React does delay to loading of the slow component. We can also specify a loading state that can be shown while it’s loading.


<xmp>
<Container>
  <Post />
  <Suspense fallback={<Spinner />}>
    <Comments />
  </Suspense>
</Container>


</xmp>

Enter fullscreen mode Exit fullscreen mode

In the above code, we wrapped the component in the . So, React not wait for the to load, It loads the other rest HTML components of the page. While loading, because we provided the component as a fallback, the HTML for the component will be sent with other HTML components of the page. Users can see spinner while comments are loading.

Once the data fetched for component, it’s HTML generated and sent to same tag that will insert <Comments∕> component to its right place.</p> <h2> <a name="looking-to-hire-reactjs-developer-contact-us-now" href="#looking-to-hire-reactjs-developer-contact-us-now" class="anchor"> </a> Looking to <a href="https://www.ifourtechnolab.com/hire-dedicated-react-developers">hire ReactJS developer</a>? Contact us now. </h2> <h2> <a name="how-to-upgrade-react-17-to-react-18" href="#how-to-upgrade-react-17-to-react-18" class="anchor"> </a> How to upgrade React 17 to React 18 </h2> <p>First, we have to install react and react-dom from npm or yarn.<br> </p> <div class="highlight"><pre class="highlight plaintext"><code> &lt;xmp&gt; npm install react react-dom &lt;/xmp&gt; </code></pre></div> <p></p> <p>or<br> </p> <div class="highlight"><pre class="highlight plaintext"><code> &lt;xmp&gt; yarn add react react-dom &lt;/xmp&gt; </code></pre></div> <p></p> <p>In React 18 createRoot is used instead of the render method with ReactDOM.</p> <p>In React 18 we create a root using the createRoot method and then render the component using this root.</p> <p>In React 17 code like this below,<br> </p> <div class="highlight"><pre class="highlight plaintext"><code> &lt;xmp&gt; import React from 'react'; import ReactDOM from "react-dom"; import App from './App'; ReactDOM.render( &lt;App/&gt;, document.getElementById("root") ); &lt;/xmp&gt; </code></pre></div> <p></p> <p>In React 18 code like this below,<br> </p> <div class="highlight"><pre class="highlight plaintext"><code> &lt;xmp&gt; import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( &lt;App /&gt; ); &lt;/xmp&gt; </code></pre></div> <p></p> <h3> <a name="conclusion" href="#conclusion" class="anchor"> </a> Conclusion </h3> <p>To summarize, React 18 will set the foundation for the next generation of releases and will emphasize improving the user&#39;s experience. We have briefly explored Concurrency, Automatic batching, startTransition API, and suspense on the server. We have also seen how to upgrade React v17.0 to React v18.o. Adopting new React 18 capabilities would result in reduced JavaScript loading and faster interaction with content.</p>

Discussion (2)

Collapse
maurice35 profile image
Maurice Kollewe T

Great post!
Harshal, thanks for sharing.

Collapse
ifourtechnolab profile image
Harshal Suthar Author

Thanks, Maurice Kollewe