Do I need to import React for stateless functional 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
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.
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.