Next.js supports ES2020 dynamic import()
for JavaScript. With it you can import JavaScript modules (inc. React Components) dynamically and work with them. They also work with SSR.
You can think of dynamic imports as another way to split your code into manageable chunks.
In the following example, the module ../components/hello
will be dynamically loaded by the page:
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/hello'))
function Home() {
return (
<div>
<Header />
<DynamicComponent />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
DynamicComponent
will be the default component returned by ../components/hello
. It works like a regular React Component, and you can pass props to it as you normally would.
If the dynamic component is not the default export, you can use a named export too. Consider the module ../components/hello.js
which has a named export Hello
:
export function Hello() {
return <p>Hello!</p>
}
To dynamically import the Hello
component, you can return it from the Promise returned by import()
, like so:
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() =>
import('../components/hello').then(mod => mod.Hello)
)
function Home() {
return (
<div>
<Header />
<DynamicComponent />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
An optional loading
component can be added to render a loading state while the dynamic component is being loaded. For example:
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello'),
{ loading: () => <p>...</p> }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
You may not always want to include a module on server-side. For example, when the module includes a library that only works in the browser.
Take a look at the following example:
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home