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

Loading

Handling React Imports in JSX Files

The Evolution of React Imports

Pre-React 17 (Classic JSX Transform)

Previously, every JSX file required an explicit React import because Babel transformed JSX into React.createElement() calls:

import React from 'react'; // Required before React 17

function Component() {
  return <div>Hello World</div>; 
  // Transpiled to: React.createElement('div', null, 'Hello World')
}

React 17+ (New JSX Transform)

The new automatic runtime eliminates the need for explicit React imports in most cases:

// No React import needed (with proper configuration)
function Component() {
  return <div>Hello World</div>;
}

When You Still Need React Imports

  1. Using React APIs directly:
   import { useState, useEffect } from 'react';

   function Counter() {
     const [count, setCount] = useState(0);
     return <div>{count}</div>;
   }
  1. Working with class components:
   import React from 'react';

   class MyComponent extends React.Component {
     render() {
       return <div>Class Component</div>;
     }
   }
  1. Using React-specific APIs:
   import { createContext } from 'react';
   const MyContext = createContext();

Configuration Requirements

For Babel Users:

{
  "presets": [
    ["@babel/preset-react", {
      "runtime": "automatic" // Enable new JSX transform
    }]
  ]
}

For TypeScript Users:

{
  "compilerOptions": {
    "jsx": "react-jsx" // Instead of "react"
  }
}

For Webpack/Vite:

Modern build tools typically support the new transform out of the box when using React 17+.

Troubleshooting Missing Imports

If you see “React is not defined” errors:

  1. Check your React version:
   npm list react
  1. Verify your Babel/TypeScript config is using the automatic runtime
  2. Temporary solution (if you can’t upgrade):
   import React from 'react'; // Explicit import as fallback

Best Practices

  1. For new projects: Use the new transform and omit React imports when possible
  2. For libraries: Include React as a peer dependency
  3. For mixed codebases: Be consistent within each file
  4. When in doubt: Import React explicitly to avoid confusion

IDE Support

Modern code editors (VS Code, WebStorm) understand the new transform and:

  • Won’t show false warnings about missing React imports
  • Will properly suggest auto-imports for React hooks and APIs
  • Maintain correct type checking in TypeScript projects

Migration Example

Before Migration:

import React from 'react';

function App() {
  return <h1>Hello World</h1>;
}

After Migration:

function App() {
  return <h1>Hello World</h1>;
}

With Hooks:

import { useState } from 'react'; // Only import what you need

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

Leave a Reply

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