N
Nuxt2mo ago
scrongly

Best way to detect hydration completion

I know nuxt provides useNuxtApp().isHydrating, but what's the best way to detect when this value returns false? I've tried wrapping a component in <ClientOnly> , then adding a computed prop for isHydrating and watching that computed, but the watcher never fires even though isHydrating returns true in the onMounted hook. What is a reliable way to detect when hydration is complete?
6 Replies
Cue
Cue2mo ago
Set a global ref to false by default. Change to true when hydration completes via a client plugin utilizing the app:suspense:resolve hook. Use it conditionally to render components, etc. Go further by creating a onHydrated hook combined with VueUse's watchOnce for simplicity. For example:
// composables/hydration.ts

export const isHydrated = ref(false)

export function onHydrated(cb: () => unknown) {
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
}
// composables/hydration.ts

export const isHydrated = ref(false)

export function onHydrated(cb: () => unknown) {
watchOnce(isHydrated, () => cb(), { immediate: isHydrated.value })
}
// plugins/hydration.client.ts

export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hooks.hookOnce('app:suspense:resolve', () => {
isHydrated.value = true
})
})
// plugins/hydration.client.ts

export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hooks.hookOnce('app:suspense:resolve', () => {
isHydrated.value = true
})
})
scrongly
scrongly2mo ago
That's a wonderful solution @cuebit @cuebit Apologies if this is a stupid question but what is being passed into onHydrated (the 'cb' arg)
Cue
Cue2mo ago
A callback (abbr. to cb) function that triggers when hydration completes. Useful when you want to run arbitrary logic within setup, or other composables without having to define a watch in multiple places or wrapping around client conditionals. For example:
onHydrated(() => {
// do something when hydration completes
})
onHydrated(() => {
// do something when hydration completes
})
scrongly
scrongly2mo ago
Ah gotcha @cuebit , again thank you so much, this works beautifully and is quite elegant!
Wild
Wild2mo ago
@cuebit just want to say that I love you
Cue
Cue2mo ago
Now that is “Wild”. Appreciate you 👍