×

iFour Logo

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

Kapil Panchal - June 26, 2022

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
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 (
    <>

{counter}

{text}

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

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 For Your Business?

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.

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"); }); 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 For Your Business? CONNECT US 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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Next-Gen Programming Languages: Shaping the Future of Software Development in 2024
Next-Gen Programming Languages: Shaping the Future of Software Development in 2024

Introduction Imagine standing in line at the grocery store, waiting to pay for groceries. You pull out your phone and scan each item’s barcode with a single tap. This seemingly...

MySQL vs Azure SQL Database: Understanding Needs, Factors, and Performance Metrics
MySQL vs Azure SQL Database: Understanding Needs, Factors, and Performance Metrics

The world of technology is constantly changing, and databases are at the forefront of this evolution. We have explored different types of databases, both physical and cloud-based, and realized how each of them provides unique features to improve data accessibility and inclusive performance. Leading the pack are MySQL and Azure SQL database services , helping business elevate their processes to new heights.

Streamlining E-commerce Operations with Microsoft PowerApps
Streamlining E-commerce Operations with Microsoft PowerApps

In today's rapidly changing digital world, eCommerce is a dynamic industry. Every day, millions of transactions take place online, so companies are always looking for new and creative methods to improve consumer satisfaction and optimize operations.