34
14

More than 1 year has passed since last update.

import React from "react" はもう要らない

Last updated at Posted at 2022-02-04

この記事は公式のIntroducing the New JSX Transformに基づいて書かれています。

結論

  • import React from "react";はReact 17以降は必要ないよ。16以前は必要だよ。
  • コンパイラが自動でインポートしてくれるようになったよ。

本編

Reactでコンポーネントのコードを書くときに、Reactをソースコードの中で特に使ってる訳ではないけど、import React from "react";って書いてますよね。

import React from 'react';

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

なぜ必要かというと、Reactコンポーネントは次のようにコンパイルされるためです。

コンパイル後
import React from 'react';

function App() {
  return React.createElement('h1', null, 'Hello world');
}

コンパイル前のコードでReactを使っていなくても、コンパイル後のコードでReact.createElementを使っているからインポートが必要なんですね。でも、React 17以降はコンパイルの挙動が変更されました。

React17以降
// 次の行はコンパイル時に自動で挿入される
import {jsx as _jsx} from 'react/jsx-runtime';

function App() {
  return _jsx('h1', { children: 'Hello world' });
}

エレメントを生成する関数がReact.createElementからjsxに変わりました。また、jsxはコンパイル時に自動でインポートされるようになりました。よって、React 17以降はimport React from "react";は書く必要がなくなったわけです。

34
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
14