How to Perform Dynamic Import with Next.js

Krishnanunny H
JavaScript in Plain English
2 min readApr 20, 2021

--

Typically, it is impossible to import modules based on the condition. Whenever a page loads, all the imported modules on that particular page also get loaded.

const allowImport = true;
if (allowImport) {
import DynamicComponent from "../components/hello";
}
export default function Home() {
return (
<div>
<DynamicComponent />
</div>
)
}

The above snippet of code will produce some errors while compiling. But with Next.js, it is possible to load modules based on conditions with the help of dynamic import. We have to import the module ‘next/dynamic’ to perform the dynamic import.

import dynamic from 'next/dynamic'
const allowImport = true;
let DynamicComponent = null;
if (allowImport) {
DynamicComponent = dynamic(() => import('../components/hello'))
}
export default function Home() {
return (
<div>
<DynamicComponent />
</div>
)
}

Even if the imported module is not the default export, we could do dynamic import.

import dynamic from 'next/dynamic'

const DynamicComponent = dynamic(() =>
import('../components/hello').then((mod) => mod.Hello)
)

function Home() {
return (
<div>
<DynamicComponent />
</div>
)
}

export default Home

In Next.js, HTML is produced on the server-side. Thus, situations like when a particular module requires a library that only works in the browser will break the code compilation. With dynamic import, we could load that particular module on the browser side only.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello'),
{ ssr: false }
)

function Home() {
return (
<div>
<DynamicComponentWithNoSSR />
</div>
)
}

export default Home

Conclusion

Dynamic import is also used to increase the website performance since we could stop loading all the files on the initial page load itself. But if you use this feature incorrectly, it could also affect the site performance.

--

--