How can I properly implement code splitting with SSR on Vite

92 Views Asked by At

I am trying to implement support for SSR in my framework and want to switch the documentation to SSR.

It's running on Vercel with Vite as bundler.

I'm using code splitting features of Vite by lazy loading my routes in order to create seperate chunks for each page.

This is working fine for a CSR build where you would expect loading indicators as the client fetches data.

If you directly navigate to a lazily loaded route and serverside rendering already serves the prerendered page then lazy loaded components will suspend during hydration..

That's because the component react-router renders suspends while it's fetching the import.

That's ok, however I don't want the page to suspend because that's causing layout shifts and flickering.

I think I have a few approaches:

  1. Somehow don't use React.lazy for this route if it's SSR.
  2. Somehow inline the code needed for that route if it's server rendered
  3. Use startTransition to keep the server rendered HTML until the client side component has been loaded and hydrated.

I'm not sure what's the best approach. I hoped the future flag for react-router to use transitions would solve this but somehow it didn't

I'm wondering how to properly implement code splitting when doing SSR and partial hydration?

I also documented my findings here, in case someone is trying to do the same.

0

There are 0 best solutions below