Dynamic imports
Next.js supports ES2020 dynamic import() for JavaScript. With it, you can import JavaScript modules dynamically and work with them. They also work with server-side rendering.
For example, you could load the module dynamically in the browser only after the user types in the search input or you just need to skip rendering some component on the server because it depends on the DOM API or client-side data.
Next.js supports dynamic imports that, when used with components, will opt out of server-side rendering. For example, if you inspect the output of the actual HTML page, you won't see the SponsoredAd component in the page source, although you can see it in the page visualization. Note: server-side rendering is false { ssr: false }
import dynamic from 'next/dynamic'
const SponsoredAd = dynamic(
() => import('../components/sponsoredAd'),
{ ssr: false }
)
const Page = () => (
<div>
<h1>This will be prerendered</h1>
{/* this won't*/}
<SponsoredAd />
</div>
)
export default Page
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
If the dynamic component is not the default export, you can use a named export too.
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:
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello'),
{ loading: () => <p>...</p> }
)
Last updated
Was this helpful?