sfletche
sfletche

Reputation: 49744

Do I need to import React for stateless functional components?

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?

Upvotes: 31

Views: 10511

Answers (4)

Andrew Li
Andrew Li

Reputation: 57974

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.

Update Sep 2021: In React 17, a new JSX transform is introduced which automatically transforms JSX without using React.createElement. This allows us to use JSX without importing React. More on docs

Upvotes: 56

Sudipta Das
Sudipta Das

Reputation: 31

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

Upvotes: 3

Foolish
Foolish

Reputation: 4202

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.

Upvotes: 24

Mayank Shukla
Mayank Shukla

Reputation: 104489

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.

Upvotes: 6

Related Questions