React入门疑问:index.js导入React却未使用的原因
import React from 'react'; Even If It's Not Used Directly? Great question! This is a super common point of confusion for new React devs, and it all boils down to how JSX gets processed behind the scenes, plus a big change introduced in React 17. Let’s break it down clearly:
Before React 17: JSX Depends on React.createElement
In React versions prior to 17, every bit of JSX you write gets compiled (usually by Babel) into explicit calls to React.createElement(). For example, your component’s JSX:
<div> Hello !!<div>
Gets transformed under the hood to something like:
React.createElement('div', null, ' Hello !!', React.createElement('div', null))
Since this compiled code directly references the React object, you have to import React at the top of your file—otherwise, the browser won’t recognize the React variable and will throw a ReferenceError. Even though you don’t write React explicitly in your JSX, the compiled code needs it to work.
React 17+: The New JSX Transform
React 17 rolled out a new JSX transform that rewires how JSX is compiled. Instead of relying on React.createElement, the transform now automatically imports special internal React functions behind the scenes—you don’t have to write the import React line yourself anymore.
That’s exactly why your code works fine without the import! In React 17 and later, you can safely omit import React from 'react'; from your files, just like you did here.
Why Do Tutorials Still Include the Import?
Lots of tutorials or older projects were built for React versions before 17, so they keep the import React statement out of habit or to maintain compatibility with older setups. As the ecosystem shifts more to React 17+, you’ll see fewer tutorials requiring this line.
A quick test to confirm: if you’re on React 17+, remove the import and your code runs smoothly. If you’re on an older version, you’ll get an error until you add the import back.
内容的提问来源于stack exchange,提问作者Sandeep P

