Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to import React for stateless functional components?

Tags:

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?

like image 561
sfletche Avatar asked May 23 '17 17:05

sfletche


People also ask

Do you need to import React for functional components?

If you use React, import React from 'react' is the first thing that you write in your code but if you have created a new react app using creat-react-app recently, you might have noticed that there is no import React statement at the top and your code works just fine.

Are functional components stateless in React?

A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.

Why need import React from React?

Explanations: The JSX gets internally into many React. createElement() function calls and each of them returns an object as shown above. Now because of this, we need to import React from “react” since internally every JSX is creating a React Component using JSX transformer. then React.

Are React components stateless or stateful?

In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components.


2 Answers

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

like image 55
Andrew Li Avatar answered Oct 30 '22 18:10

Andrew Li


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.

like image 26
Foolish Avatar answered Oct 30 '22 18:10

Foolish