Tech

Steps to Upgrade to React 18

Steps to Upgrade to React 18

React 18 was released early this year with several noteworthy upgrades and intriguing new features! As a leading ReactJS development company, we always use latest tech. Concurrent React and Suspense are two great recent additions. Given that we have covered these features in great detail, let’s move on to the upgrading process to React 18!

The transition from older versions of React to React 18 has been made as simple as possible courtesy of a number of newly designed hooks and features in React 18. React 18 should be easy to upgrade to, ideally taking under a minute. I’ll walk you through the procedure for updating your projects to React 18.

Installing React 18

The procedure for updating your projects to React 18 is rather simple. Although the majority of new features are designed to be easily adopted, Suspense and Transitions, among other new features, would not function satisfactorily without React 18. To make the most of the newest capabilities, you must upgrade your app to React 18.

How can React 17 be upgraded to React 18? One simple step can complete the task. Once your project is open, you add this command

 npm install react react-dom

This would update React on your project to the most recent version, which in this case is React 18.0. You must enter this command if you are using yarn

yarn add react react-dom

This is all there is to installing React 18! Your app would now be able to use the new features of React 18 because React 18 would be installed automatically.

reactDOM.render is no longer supported will appear in error messages after installing React 18.

You would need to import create.Root from react-dom/client to fix this problem. You could unmount and create a new root in this way. Please be aware that skipping this step will result in your app continuing to behave as though it were still using React 17. If you don’t import the create.Root function, upgrading to React 18 won’t change anything in your code!

New APIs You Need to Import to Work in React 18

Even after installing React 18, there are still a few APIs you’ll need for your project to function with React 18. In the latest iteration, some functions are also anticipated to operate differently. Let’s examine each one separately.

Client Rendering APIs

React 18 introduces a new root API. This development’s main objective is to enhance React 18’s overall usability and root handling. Additionally, to use the novel Concurrent capabilities of React 18 in your app, you would be required to invoke this root API.

// Before

import { render } from ‘react-dom’;

const container = document.getElementById(‘app’);

render(<App tab=”home” />, container);

// After

import { createRoot } from ‘react-dom/client’;

const container = document.getElementById(‘app’);

const root = createRoot(container); // createRoot(container!) if you use TypeScript

root.render(<App tab=”home” />);

unmountComponentAtNode is substituted by root.unmount in React 18

// Before

unmountComponentAtNode(container);

// After

root.unmount();

Suspense, a brand-new feature in React 18, was suspected to cause callback in render to malfunction before being proven to be true. This is why React 18 removes the callback function from render. The render callback API currently has no direct replacement.

// Before

const container = document.getElementById(‘app’);

render(<App tab=”home” />, container, () => {

  console.log(‘rendered’);

});

// After

function AppWithCallbackAfterRender() {

  useEffect(() => {

    console.log(‘rendered’);

  });

  return <App tab=”home” />

}

const container = document.getElementById(‘app’);

const root = createRoot(container);

root.render(<AppWithCallbackAfterRender />);

In React 18, hydrate.root replaces ReactDOM.hydrate. You would need to import hydrate.root in the latest version of React if your project needs hydration for server-side rendering.

// Before

import { hydrate } from ‘react-dom’;

const container = document.getElementById(‘app’);

hydrate(<App tab=”home” />, container);

// After

import { hydrateRoot } from ‘react-dom/client’;

const container = document.getElementById(‘app’);

const root = hydrateRoot(container, <App tab=”home” />);

// Unlike with createRoot, you don’t need a separate root.render() call here.

Changes in Strict Mode

In React 18, the <StrictMode> is more strict! After you upgrade them to react 18, it’s possible that some of your projects won’t function. You would need to determine whether the projects that don’t work with React 18 are wrapped with <StrictMode> in order to get around this issue. If they are, turning off Strict Mode while upgrading may make your previous apps compatible with React 18. You can once more wrap your code, or a portion of it, in strict mode after the upgrade is complete. That is, only after fixing the problems that were preventing your code from working!

It is crucial to note that new iterations of React in the future will be improved in terms of sensitivity to UI inputs. The Strict Mode in React 18 now includes a development-only test to help identify any potential problems that may arise from implementing these improvements. Every component in your application will automatically be unmounted and remounted by this feature when it is mounted for the first time. During the second mount, the component will be remounted in its prior state.

* React mounts the component.

    * Layout effects are created.

    * Effect effects are created.

* React simulates unmounting the component.

    * Layout effects are destroyed.

    * Effects are destroyed.

* React simulates mounting the component with the previous state.

    * Layout effect setup code runs

    * Effect setup code runs

Server Rendering APIs

  • In React 18, all react-dom/server APIs have been substantially rebuilt to allow both Streaming SSR and Suspense on the server. For this basis, the previous Node streaming API has been discontinued. Because progressive Suspense server streaming was not supported by this API, this was implemented. The following warning will now be shown while using the Node Streaming API: renderToNodeStream
  • We now need to use renderToPipeableStream in Node environments to stream.
  • Additionally, a new API,  renderToReadableStream, is made available to facilitate Suspense streaming on servers using environments like Deno and Cloudflare.
  • Whilst they continue to function, the APIs mentioned next now have restricted functionality with Suspense:
    • renderToString
    • renderToStaticMarkup
  • For email rendering, the renderToStaticNodeStream API would continue to work.

Changes in TypeScipt Definition

When upgrading to React 18, you will need to make certain adjustments if your project uses TypeScript. The @types/react and @types/react-dom dependencies in React 18 have been updated, which is the most significant change. These are generally safer and are better at spotting bugs.

The other significant change is the requirement to explicitly list the children prop when listing the other props. For instance:

interface MyButtonProps {

  color: string;

 children?: React.ReactNode;

}

Automatic Batching

React 18 now has a brand-new functionality called Automatic Batching. You need only import create.root to instruct React 18 to batch your code automatically when you enable automatic batching in your project.

// After React 18 updates inside of timeouts, promises,

// native event handlers or any other event are batched.

function handleClick() {

  setCount(c => c + 1);

  setFlag(f => !f);

  // React will only re-render once at the end (that’s batching!)

}

setTimeout(() => {

  setCount(c => c + 1);

  setFlag(f => !f);

  // React will only re-render once at the end (that’s batching!)

}, 1000);

To opt-out of automatic batching in your code, use flushSync.

import { flushSync } from ‘react-dom’;

function handleClick() {

  flushSync(() => {

    setCounter(c => c + 1);

  });

  // React has updated the DOM by now

  flushSync(() => {

    setFlag(f => !f);

  });

  // React has updated the DOM by now

}

New Library APIs

In React 18, new APIs have been added with library maintainers in mind. The APIs would make it possible to employ concurrent rendering, a new React feature, for particular purposes. Let’s talk about these APIs in brief.

  • UseSyncExternalStore makes concurrent changes to the store possible by enabling concurrent reads of external stores.
  • useInsertionEffect makes it possible for CSS-in-JS libraries to fix technical glitches brought by injecting styles while rendering.

Setting up Testing Environment

We’ve discussed the modifications to your code that you’ll need to do in the earlier sections in order for React 18 to operate with your existing code. We’ll discuss the adjustments you’ll need to make to your testing environment when using React 18 in this section.

When you attempt to upgrade your tests using create.root, the following error will appear in your test console:

The current testing environment is not configured to support React 18

You would need to switch globalThis.IS REACT ACT ENVIRONMENT to true in order to avoid this problem. This would signal to React that your code is being executed in a setting similar to a unit test. React will not mark warnings when an update is not wrapped in act if you turn this flag to false.

Don’t Keep Using these APIs

Even though we have just discussed every deprecated API in React 18, let’s recapitulate by taking a look at the entire list of deprecated APIs in React 18. Please remember to stop using these APIs after upgrading to React 18. If you use them, your code will either execute in React 17 or it won’t work altogether.

  • react-dom: ReactDOM.render
  • react-dom: ReactDOM.hydrate
  • react-dom: ReactDOM.unmountComponentAtNode
  • react-dom: ReactDOM.renderSubtreeIntoContainer
  • react-dom/server: ReactDOMServer.renderToNodeStream

Finishing the process

Upgrade to React 18: React 18 has several new features that interact with one another to improve the responsiveness of apps created using this most recent version of the framework. React 18 is incredibly easy to upgrade to, and it shouldn’t take more than a few seconds. We will need to make some modifications to the code to convert our older apps to React 18 and thereafter utilize all of its new features. React has brought various new APIs that we can easily include into our program to make this process simple. This would make it possible for our code to fully utilize React 18. As the new APIs take their place, some APIs are also deprecated. Upgrading to React 18 will be a piece of cake if you remember these.

The React library, which was released with React 18, has undergone many interesting new modifications. Upgrade to the most recent version and enjoy yourself!

Also Read: Top Must-Have Shopify Apps To Increase Sales In 2022

Share this post

Leave a Reply

Your email address will not be published.