DEV Community

Cover image for Removing Default React Imports. For a Cleaner Code
Alex
Alex

Posted on • Originally published at buaiscia.github.io

Removing Default React Imports. For a Cleaner Code

Photo by Liliana Drew: https://www.pexels.com/photo/a-person-vacuuming-under-a-side-cabinet-9462147/

If you are one of the many people migrating their projects to React 18, maybe you skipped one great feature for your code coming along from the previous version (17): you can remove all default React imports!
To be precise, it was present also in some previous React versions, but it was always somehow hidden from the general public (or maybe just me?).

We were accustomed to the need of importing React in every. single. file.
And maybe you are still doing it after the migration. I did it, indeed, for a while :D

That is because this possibility is in the docs, but on a side note with an enigmatic title: "Introducing the new JSX transform".

In substance, it creates React as a global so it does not need to import it everywhere. How does it work?
It is quite simple. Instead of having:

import React, {useState, useEffect} from 'react'
Enter fullscreen mode Exit fullscreen mode

you can have the normal destructured import without the need to import the whole library:

import {useState, useEffect} from 'react'
Enter fullscreen mode Exit fullscreen mode

or skip it entirely if you don't need any hook.

Also, instead of removing all those imports manually, React offers an automated script that will make everything for you:

npx react-codemod update-react-imports
Enter fullscreen mode Exit fullscreen mode

Just be careful to have all your work committed, as it will create changes probably on almost every file of your repository.

What about linting?

There was another small problem. Eslint was complaining if one was removing React from a file, saying it was not a UMD global.

The missing piece is on this page, in a small note at the end of the page: the eslint rule to disallow missing React when using JSX.

At the bottom, there is a paragraph. If you are using the new JSX transform from React 17, you should disable this rule, adding "plugin:react/jsx-runtime" to "extends" in the eslint config file.

Now everything will work as expected and you will have a much cleaner codebase!

Thank you for reading! Let's connect on Twitter

Top comments (0)