Do you know when to use dynamic imports in Next.js?

Last updated by Brady Stroud [SSW] 10 months ago.See history

Components with large imports loaded in on runtime may result in a much worse UX for users of your web app. Next.js can help with this by using dynamic imports to only load these large components when they are rendered on the page.

When using the Next.js pages router, we can use next/dynamic to lazy load components, based on React's React.lazy and Suspense.

const HeavyComponent = dynamic(import("./components/HeavyComponent"), {
  loading: () => <p>Loading...</p>
});

export const Page = () => {
  const [showComponent, setShowComponent] = useState(false);

  return (
    <>
      ...
      {showComponent && <HeavyComponent />}
      ...
    </>
  )
}

This means that the <HeavyComponent> element will only be loaded in when the showComponent state variable is true. When condition is then set to true, the paragraph component in the loading field will display until the component has been loaded onto the page.

This works by packing the heavy component into a separate JavaScript bundle, which Next.js then sends to the client when the showComponent variable is true.

You can learn more about how to use next/dynamic in the official Next.js documentation.

We open source. Powered by GitHub