A New Era for React: Say Goodbye to Importing React

What is JSX, Anyway?

If you’ve ever written React, you’ve probably noticed the strange HTML-like syntax in your JavaScript files. That’s JSX, a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. However, JSX is not valid JavaScript, so it needs to be compiled into valid JavaScript code using a tool like Babel or TypeScript.

The Old Way: Importing React

Before React 17, when you wrote JSX code, it would get compiled into calls to the React.createElement function. This meant that you needed to import React at the top of every file, which was a hassle for both beginners and experts.

import React from 'eact';

const element = <div>Hello World!</div>

The New Way: Automatic Imports

With React 17, the JSX transform has been updated to automatically import a new jsx function from a custom entry point. This means that your compiled code will look like this:

const element = <div>Hello World!</div>

No more importing React! This change also has the nice side effect of potentially reducing your bundle size.

What Do I Need to Do?

To take advantage of this new feature, you’ll need to:

  • Upgrade to React 17 or later.
  • If you’re using a framework like Create React App, Next.js, or Gatsby, update to a compatible version.
  • If you’re using a custom Babel config, update your presets and plugins.

Removing Old Imports

Once you’ve upgraded, you’ll still have old imports hanging around. Don’t worry, everything will still work as normal, but it’s a good idea to remove them to keep your code clean. The React team has provided an automatic script to help you do just that.

The Benefits

With this change, React just got a whole lot easier to learn and use. No more remembering to import React, and no more extra lines of code to write. It’s a small change, but it makes a big difference.

Leave a Reply