E-Kuerschner / useAudioPlayer

React hooks for controlling audio on the web
MIT License
315 stars 35 forks source link

Warning: useLayoutEffect does nothing on the server #44

Closed humbkr closed 3 years ago

humbkr commented 3 years ago

I use useAudioPlayer in a Next.js project and the useAudioPosition triggers a lot of warning in the logs of the server:

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://fb.me/react-uselayouteffect-ssr for common fixes.

which makes reading the logs difficult.

One of the solution is to create a wrapper:

import { useEffect, useLayoutEffect } from 'react'

const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect

export default useIsomorphicLayoutEffect

@E-Kuerschner if you're okay with this solution, I can implement it.

E-Kuerschner commented 3 years ago

@humbkr once the browser takes control it will be using useLayoutEffect right? I don't do too much server rendering tbh so you will have to fill in the gaps a bit. There's no actual logic that is running on the server side right? It's just setting up initial state and whatnot? Because the layout effect actually had an impact on the animation logic if I recall.

humbkr commented 3 years ago

Yes, basically useEffect can run on the server, but useLayoutEffect cannot, hence the warning. useIsomorphicLayoutEffect will just use useEffect server side so react is happy, and when the code will be executed on the client it will use useLayoutEffect.

E-Kuerschner commented 3 years ago

i think an ideal solution would be to suppress those warnings if possible (maybe with a flag in Next.js), but that seems unlikely. I'm cool with the solution proposed - feel free to throw up a PR when ready

humbkr commented 3 years ago

I had a look at a component library and they used the same method, they use an abstraction layer for useLayoutEffect to manage SSR.

E-Kuerschner commented 3 years ago

@humbkr released in v1.2.1