×
iFour Logo

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

iFour Team - June 26, 2022

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

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

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

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;



After fetch call

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




In setTimeOut

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



Native event handlers

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


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.


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);
        }}
      />
    </>
  );
};




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.


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);
        }}
      />
    </>
  );
};


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.


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



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

Once the data fetched for <Comments∕> component, it’s HTML generated and sent to same <script∕> tag that will insert <Comments∕> component to its right place.

Looking to hire ReactJS developer ? Contact us now.

How to upgrade React 17 to React 18

First, we have to install react and react-dom from npm or yarn.


npm install react react-dom

or

 

yarn add react react-dom

In React 18 createRoot is used instead of the render method with ReactDOM.

In React 18 we create a root using the createRoot method and then render the component using this root.

 

In React 17 code like this below,


import React from 'react';
import ReactDOM  from "react-dom";
import App from './App';

ReactDOM.render(
  <App/>,
  document.getElementById("root")
);


In React 18 code like this below,



import React from "react";
import ReactDOM from "react-dom/client";

import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <App />
);



Conclusion

To summarize, React 18 will set the foundation for the next generation of releases and will emphasize improving the user'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.

React v18.0: A guide to its new features and updates Table of Content 1. Introduction 2. Concurrency in React 18 3. Automatic Batching 4. StartTransition API 5. Suspense on the server 6. How to upgrade React 17 to React 18 7. Conclusion 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 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 ( {counter} {text} Change ); } export default App; After fetch call const handleClick = () => { fetch("YOUR_API_URL").then(()=>{ setCounter(0); setText("After Update") }) }; In setTimeOut const handleClick = () => { setTimeout(() => { setCounter(0); setText("After Update"); }, 5000); }; Native event handlers const el = document.getElementById("button"); el.addEventListener("click", () => { setCounter(count + 1); setText("After Update"); }); 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. 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 && Loading....} { handleChange(e); }} /> ); }; 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. 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 ( { handleChange(e); }} /> ); }; 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. }> In the above code, we wrapped the <Comments∕> component in the <Suspense∕>. So, React not wait for the <Comments∕> to load, It loads the other rest HTML components of the page. While loading, because we provided the <Spinner∕> component as a fallback, the HTML for the <Spinner∕> component will be sent with other HTML components of the page. Users can see spinner while comments are loading. Once the data fetched for <Comments∕> component, it’s HTML generated and sent to same <script∕> tag that will insert <Comments∕> component to its right place. Looking to hire ReactJS developer ? Contact us now. See here How to upgrade React 17 to React 18 First, we have to install react and react-dom from npm or yarn. npm install react react-dom or   yarn add react react-dom In React 18 createRoot is used instead of the render method with ReactDOM. In React 18 we create a root using the createRoot method and then render the component using this root.   In React 17 code like this below, import React from 'react'; import ReactDOM from "react-dom"; import App from './App'; ReactDOM.render( , document.getElementById("root") ); In React 18 code like this below, import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( ); Conclusion To summarize, React 18 will set the foundation for the next generation of releases and will emphasize improving the user'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.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Top 8 Developing Technologies that are making headlines in 2022
Top 8 Developing Technologies that are making headlines in 2022

Table of Content 1.Cybersecurity 2.Robotics and Automation 3.Progressive Web Apps 4.Artificial Intelligence and Machine Learning 5.Metaverse 6.5G Technology Adoption 7.Datafication...

Read More
How Artificial Intelligence (AI) can Boost Your eCommerce Sales in 2022
How Artificial Intelligence (AI) can Boost Your eCommerce Sales in 2022

Table of Content 1.AI improves retargeting leads 2.AI decreases Cart Abandonment rate 3.AI chatbot to enhance customer experience 4.AI assists in understanding customer...

Read More
Angular vs Backbone: Which Frontend framework is the best in 2022?
Angular vs Backbone: Which Frontend framework is the best in 2022?

Table of Content 1.What is Angular? 2.Features of Angular.js 3.When to use Angular? 4.What is Backbone? 5.Backbone.js features 6.When to use backbone? 7.Backbone.js...

Read More