Skip to content

Instantly share code, notes, and snippets.

@thanhlmm
Last active March 9, 2022 00:09
Show Gist options
  • 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

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