The Classic Problem (Pre-React 17)
Before React 17, you needed to import React in every file using JSX because JSX was transformed into React.createElement()
calls:
// Required pre-React 17
import React from 'react';
function MyComponent() {
return <div>Hello World</div>;
}
Without this import, you’d get the error: ‘React’ must be in scope when using JSX.
The Modern Solution (React 17+)
React 17 introduced a new JSX transform that automatically imports the necessary functions, eliminating the need for explicit React imports:
// No React import needed in React 17+
function MyComponent() {
return <div>Hello World</div>;
}
How to Set Up the New JSX Transform
1. For Create React App (v4+)
Already configured by default – no setup needed.
2. For Custom Webpack Configs
Update your Babel config:
npm install @babel/preset-react@^7.12.0
// babel.config.json
{
"presets": [
["@babel/preset-react", {
"runtime": "automatic"
}]
]
}
3. For TypeScript (v4.1+)
Update tsconfig.json
:
{
"compilerOptions": {
"jsx": "react-jsx"
}
}
When You Still Need React Imports
Even with React 17+, you’ll need to import React when:
- Using React APIs directly:
import { useState, useEffect } from 'react';
- Using React Context
- Working with older codebases
Migration Tips
- Check your React version:
npm list react
- Update ESLint rules if needed:
"rules": {
"react/react-in-jsx-scope": "off"
}
- Run a codemod to remove unused imports:
npx react-codemod update-react-imports
Common Errors and Fixes
- “React is not defined”:
- Update to React 17+ and configure the new transform
- Or add the React import if staying on older versions
- Build tool errors:
npm update @babel/core @babel/preset-react
- TypeScript errors:
npm update typescript @types/react @types/react-dom
The new JSX transform is now the standard for all modern React development, resulting in cleaner component files and slightly smaller bundle sizes.