Skip to content

Instantly share code, notes, and snippets.

@thanhlmm
Last active March 9, 2022 00:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thanhlmm/1ca92b01db81026b920f470b3564cfd1 to your computer and use it in GitHub Desktop.
Save thanhlmm/1ca92b01db81026b920f470b3564cfd1 to your computer and use it in GitHub Desktop.
Lazy load and lazy hydrate Nextjs component
import dynamic from 'next/dynamic';
import withHydrationOnDemand from 'react-hydration-on-demand';
export default function lazyLoadHydrate<T = Record<string, never>>(
module,
ssr = false,
loading = () => <span>Loading</span>,
) {
return withHydrationOnDemand({
on: ['visible'],
onBefore: module // Make sure we load component before hydrating it
})(dynamic(module, { loading, ssr }));
}
@thanhlmm
Copy link
Author

thanhlmm commented Oct 7, 2021

How to use?

const NewsletterSignupV2 = lazyLoadHydrate(
  () => import('../NewsletterSignupV2'),
  true,
  () => <div style={{ height: 300 }} />,
);

const Pages = () => {
  return <NewsletterSignupV2 />
}

@thanhlmm
Copy link
Author

thanhlmm commented Oct 8, 2021

@thanhlmm
Copy link
Author

https://twitter.com/ScriptedAlchemy/status/1450018915401158658

After discussion with Zack Jackson, this approach still has drawback, it gonna flashing when dynamic loading the chunk

@thanhlmm
Copy link
Author

What if I used ReactDOMServer to make Loading component, so we can prevent the flash? 🤔

@thanhlmm
Copy link
Author

thanhlmm commented Nov 1, 2021

Updated v2 with

onBefore: module

By wait chunk code to load before hydrating, we can prevent flashing on client side

@solarkraft
Copy link

solarkraft commented Mar 8, 2022

Looking good! Could you shine some light on how to control when the hydration data gets lazy loaded?

Edit: Got it, it depends on when react-hydration-on-demand wants to hydrate. The key is the on:.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment