Forgetting to import React when using JSX (React 17+ solves this)

Loading

Forgetting to Import React in JSX

The Classic Error

Before React 17, you’d encounter this error when forgetting to import React:

'React' must be in scope when using JSX

React 17+ Automatic Runtime

Good news: Since React 17 (released October 2020), you don’t need to explicitly import React just to use JSX, thanks to the new JSX transform.

How It Works

  1. No React import needed for basic JSX:
function MyComponent() {
  return <div>Hello</div>; // Works without React import
}
  1. Still need imports for React APIs:
import { useState } from 'react'; // Still required for hooks

function Counter() {
  const [count, setCount] = useState(0);
  return <div>{count}</div>;
}

When You Still Need React Import

  1. Using React APIs directly:
import React from 'react'; // Required for React.memo, React.createElement, etc.

const Memoized = React.memo(MyComponent);
  1. Legacy projects (pre-React 17):
import React from 'react'; // Required in older versions

function OldComponent() {
  return <div>Works only with React import</div>;
}

Configuration Requirements

For the new JSX transform to work, ensure:

  1. React 17+ is installed
  2. Your build tool is configured properly:
  • Babel: Use @babel/preset-react with runtime: 'automatic'
   {
     "presets": [
       ["@babel/preset-react", {
         "runtime": "automatic"
       }]
     ]
   }
  • TypeScript: Use jsx: 'react-jsx' in tsconfig.json
   {
     "compilerOptions": {
       "jsx": "react-jsx"
     }
   }

Migration Tips

  1. Update your configs to use the new JSX transform
  2. Remove unnecessary React imports (they’re now optional)
  3. Keep React imports when using React-specific APIs
  4. Check your ESLint config – update react/jsx-uses-react and react/react-in-jsx-scope rules

Common Mistakes

  1. Assuming all React imports can be removed (hooks and APIs still need imports)
  2. Not updating build tools (leads to runtime errors)
  3. Mixing old and new syntax in a codebase

The new JSX transform is backward compatible, so you can migrate gradually.

Leave a Reply

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