Next.js: Execute async code before hydration on client-side

Viewed 349

I need to load a dayjs locale dynamically on the client side. On the server, I can just require it and it works, but it will always lead to a hydration mismatch because there's no way on the client to wait until the

import(`dayjs/locale/${locale}.js`)

actually completes. Can I somehow tell next to wait for the import before beginning re-hydration on the client (since the server-rendered html is actually correct and rendered with the correct locale)?

1 Answers

I know it has been too long and probably you found the solution but here it is a custom hook I wrote which accepts a callback as an argument and will be called only once before rendering the component. and also returns whatever you return in the callback.

the code is simple. you can read and understand it or even improve it.

the code is right here. the gist page

the typescript code if the link gets broken in future:

const useComponentWillMount = <T>(cb: () => T): T => {
    const isMountedRef = useRef(false)
    const resultRef = useRef<T>()

    if (!isMountedRef.current && typeof window !== "undefined") {
        resultRef.current = cb()
    }

    isMountedRef.current = true

    return resultRef.current
}
Related