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?
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With