简体   繁体   中英

NextJS Dynamic Import of SSR component

Looking at the manner in which one can import react components in NextJS:

  1. Plain old static import:
import Component from './Component';
[...]
return (
  <Component />
)
  1. Dynamic import:
import dynamic from 'next/dynamic'

const DynamicComponent = dynamic(() =>
  import('../components/hello').then((mod) => mod.Hello)
)
[...]
return (
  <DynamicComponent />
)
  1. Dynamic import with ssr = false:
import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)
[...]
return (
  <DynamicComponentWithNoSSR />
)

My question is simple: When is the 2nd option the preferred option? (In all three cases, imagine that SSR is enabled through the presence of getServerSideProps.)

It seems that in any case my component is client-side-only or triggered by a user action, I'd want Option #3. And it seems that in any case it needs to be SSR'd, if I choose option #2, the chunk file gets downloaded immediately, during the before-hydration phase, so it doesn't appear to be saving me any time. It just appears to add a network call. So why wouldn't I just use Option #1?

What's the actual use case for Option #2?

The best option will depend on whether the content is server-side or client rendered. The most common way in Next for client rendered content is static generation.

However, in Next, you can also mix client and server-side rendering in pages, so it will depend on where the dynamic import executes, on the server or client.

Next also prefetches dynamic content by default, probably where a little of your original confusion lies in your code. The main content is loaded, then it's prefetched – automatically loads the dynamic content shortly after the main content.

Because of this, you'd enable SSR if the dynamic import is happening on the server. Enabling SSR disables prefetching on the server and ensures that the code fires in the proper order - I don't know if it does much extra. For example, it won't import dynamic content until the code hits the client. If you really want to dig into what's the code is doing, here's the source location in GitHub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM