'Importing react into pages in next.js (and also React and CRA apps)
I have a Next.js app with several pages in it. All of the pages look similar.
import React, { Component } from "react";
import from "components/Wrapper";
export default class About extends Component {
render() {
return <Wrapper />;
}
}
I would like to refactor it using functional component.
I read here that you don't have to import react package here in a page due to next.js routing system. Next.js docs also show examples without react import on a page component, but no explanation given.
Can you clarify please. Is it necessary to import React at all in this case? Can I remove the import React line?
Solution 1:[1]
Well, actually it is still a complicated issue for all of us to realise when to use import React from "react";
and when not to in Next.js apps. But according to Tim Neutkens co-author of Next.js, in this thread he mentioned:
Next.js automatically adds the React import when JSX is used indeed. However, keep in mind that we still need to
import React from 'react'
when the React variable is used.
So this will show us, that whenever we want to use the JSX feature alone from React we do not have to import React from 'react'
and Next.js will implicitly import it for us, but in any other case, we have to do that.
Update
Since the release of react v17.*.*
, there is no need to import React from 'react'
to use only JSX in the React and CRA apps, but you still need to import it for the usage of the hooks and other compartments that React offers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |