Do I need to import React in functional components?
This question came in mind while I was writing a Redux action and I was exporting as default a function, as usual, and then I jumped into creating a new functional component for my app.
I realised that I doing almost the same thing in both files and I started to research why do I need to import React in a component, that it’s basically a JS function.
What I firstly found out was about JSX, and how Babel converts our code from:
to:
and, if I wouldn’t import React, the React.createElement
will no work and crash my app.
I was a pretty obvious thing after I realised the process under the hood.
Than I land up on reactjs.org where I found out about the New JSX Transform.
This new feature allow us to write a simple functional component without importing React. I’m saying simple because if we need to use Hooks or other exports that React provides, we’ll need to import React also.
How is that happening? JSX transform will compile:
notice that I’m not importing React*
to:
That being said, a small and simple functional component doesn’t need to import React anymore.
You can find out more here:
https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html