Last active
March 9, 2022 00:09
-
-
Save thanhlmm/1ca92b01db81026b920f470b3564cfd1 to your computer and use it in GitHub Desktop.
Lazy load and lazy hydrate Nextjs component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 })); | |
} |
https://twitter.com/ScriptedAlchemy/status/1450018915401158658
After discussion with Zack Jackson, this approach still has drawback, it gonna flashing when dynamic loading the chunk
What if I used ReactDOMServer
to make Loading component, so we can prevent the flash? 🤔
Updated v2 with
onBefore: module
By wait chunk code to load before hydrating, we can prevent flashing on client side
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
How to use?