What is the benefit of SSR: true prop with dynamic imports?

Viewed 698

What is a difference between dynamic imported component with ssr: true:

const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), {
  ssr: true,
});

and just normal component import:

import { Button } from './Button';
  • What is the benefit of one over the other?
  • Where do we put load on?
  • For scenario below (JSX example), if showButton is false, did we still load DynamicButton and where?

// jsx
return showButton && <DynamicButton />
1 Answers

Regular import

When using a regular component import, Next.js bundles the component's code together with the rest of the components for a given route. This usually means you end up with a big chunk containing all the components code for each route.

next/dynamic with ssr: true

When using next/dynamic with ssr: true, Next.js splits the component's code into a separate chunk (code splitting) and loads that chunk separately (lazy loading).

This means that for the scenario that you described:

return showButton && <DynamicButton />

The DynamicButton component only gets loaded when showButton is truthy. This has the benefit of reducing the amount of JavaScript that's loaded on initial page load.

next/dynamic with ssr: false

When using next/dynamic with ssr: false, all the above benefits of the dynamic import also apply. However, the component's code will not get preloaded on the server and will only run on the client. This is typically useful when the component includes a library or API that only works in the browser.

Related