Upgrading to React 18: A Guide to Breaking Type Changes

React 18 has finally shipped, bringing with it a host of exciting new features and improvements. However, this major update also introduces some significant breaking changes that may affect your codebase. In this article, we’ll delve into the world of type definitions and explore how to upgrade your React application to version 18.

The Problem with Definitely Typed and Semantic Versioning

Definitely Typed (DT) is a repository for high-quality TypeScript type definitions. While DT does an excellent job of providing accurate type definitions, it doesn’t support semantic versioning. This means that when a new version of a library is released, the corresponding type definition package won’t necessarily receive a major version bump.

Breaking Type Changes in React 18

When Sebastian Silbermann submitted a pull request to upgrade the TypeScript React type definitions, he took the opportunity to make some breaking changes. These changes were not directly related to React 18, but rather fixed long-standing issues with the React type definitions. Some of the most notable breaking changes include:

  • Removal of implicit children
  • Remove {} from ReactFragment
  • this.context becomes unknown
  • Using noImplicitAny now enforces a type is supplied with useCallback
  • Remove deprecated types to align with official React ones

Upgrading Your Codebase

To demonstrate what upgrading looks like, let’s take a simple website as an example. The first step is to upgrade React itself in the package.json file. Next, we’ll upgrade our type definitions by running the following command:

bash
npm install --save-dev @types/react@18 @types/react-dom@18

Once the installation is complete, we may start to see error messages like this:

Property 'children' does not exist on type 'LoadingProps'.ts(2339)

This is because the removal of implicit children is now in effect. To fix this issue, we need to explicitly declare the children property on our components.

Using Codemods to Simplify the Upgrade Process

Fortunately, Sebastian Silbermann has provided a codemod to help with the upgrade process. By running the following command, we can automatically add the children property to our components:

bash
npx @typescript-eslint/codemod add-children-prop

This will prompt us to select the files we want to update, and then apply the necessary changes.

Conclusion

In conclusion, upgrading to React 18 requires some careful attention to breaking type changes. By understanding these changes and using tools like codemods, we can simplify the upgrade process and ensure a smooth transition to the latest version of React.

Leave a Reply

Your email address will not be published. Required fields are marked *