Skip to main content

import React from 'react'

import React from 'react'

is a JavaScript statement to bring the React library into your file, historically required to use JSX (like <div>) because it converts to React.createElement(), though newer React versions with the "new JSX transform" (React 17+) often make it optional for basic JSX, but it's still needed for Hooks (like useState) and other exports, with import * as React from 'react' also common for importing everything into a React object. 



What it does

  • Imports React: It makes the React object, containing methods like createElement, available in your component.
  • Enables JSX: Before React 17, this line was essential because JSX syntax (e.g., <p>Hello</p>) gets transformed into React.createElement(<p>, null, 'Hello'). 

Modern variations and when to use them

  • import React from 'react': Imports the default export (the whole library) and names it React. Still needed for Hooks.
  • import * as React from 'react': Imports all named exports into a single React object. Useful in TypeScript or with specific bundler setups.
  • No import (for simple components): With React 17+, the new JSX transform handles basic JSX without needing the import, but you still need it for hooks.
  • Specific imports: For efficiency, import only what you need, e.g., import { useState } from 'react'. 

Example (Classic)
import React from 'react'; // Required for React.useState

function Counter() {
  const [count, setCount] = React.useState(0); // Uses React.useState
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Example (Modern - no import needed for basic JSX)

// import React from 'react'; // Not strictly needed for just JSX

function Greeting({ name }) {
  // No React. prefix needed for useState with this setup
  return <h1>Hello, {name}!</h1>;
}