16
votes

All around me (e.g. blog posts, code) I see code for React stateless functional components in which React is imported even though it's never used.

import React from 'react';

function MyComponent() {
  return <div>Howdy!</div>;
}

export default MyComponent;

I'm wondering why we need to import React when it's not actually used (in any explicit manner).

I'm also surprised that my linter doesn't complain about the un-used import.

Is there some reason to import React into functional components that I'm not aware of?

4
Did you actually try to transpile it? I mean, intellectual arguing is all well and good, but simply trying it would have answered the question. - Dave Newton
The ESLint React plugin, eslint-plugin-react, exposes the rule react/react-in-jsx-scope to ensure you have React in scope when using JSX because the compiled code referencesReact. The description of that rule also answers your question. The react/jsx-uses-react rule prevents React from being marked as unused. - Ross Allen
@DaveNewton: works fine on my system. that's why i was confused... - sfletche
Without the import? I don't see how. - Dave Newton
@DaveNewton: i'm guessing Babel handles it under the hood - sfletche

4 Answers

34
votes

Yes, there is. Babel transpiles JSX to use React:

<div></div>

To:

React.createElement("div", null);

So your JSX is internally transpiled to use React.createElement in pure JavaScript, which does use React. Remember that JSX is just syntactic sugar over pure JavaScript. If you don't specifically import it, it will report that React isn't defined.

6
votes

As of now you don't need to import React from 'react'; for functional components. Why you needed it is well explained in accepted answer.

This official blog post https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html explains why it was needed and now after version 17 it is no longer needed.

5
votes

What exactly a React Stateless Functional Component is?

When you write a stateful component it has basic these three parts (other than all the logic):

1. constructor

2. lifecycle methods

3. render

And react convert this render part into:

React.createElement(element, null); //element will be the wrapper of all the jsx

Now when you write a Stateless Functional Component it basically has only a render part no constructor, no lifecycle method. Whatever you return from this component will also get converted into:

React.createElement(element, null);

So that's why importing React is required. Always keep in mind that we write JSX not html, that will get transpiled by babel.

Check the DOC for React without JSX.

Check the converted version of a functional component by Babel.

Hope this will help you.

0
votes

No, you don't need to, React 17 does it automatically with the help of out of the box JSX Transform.

Find this article here