Safari Won't Play Videos via React useEffect
August 27, 2020TL;DR
View this example in Safari to see how playing a video via
useEffect
won’t work. If you’re attempting to make a video play inside a React effect, useuseLayoutEffect
.
useEffect vs useLayoutEffect
The React docs have the following tip that calls out when you should use useLayoutEffect
vs useEffect
:
Unlike
componentDidMount
orcomponentDidUpdate
, effects scheduled withuseEffect
don’t block the browser from updating the screen. This makes your app feel more responsive. The majority of effects don’t need to happen synchronously. In the uncommon cases where they do (such as measuring the layout), there is a separateuseLayoutEffect
Hook with an API identical touseEffect
.
In my experience, it’s pretty obvious when running an effect that should be a layout effect, such as the measuring example called out in the React docs. And the even though the behavior of useEffect
is slightly different in timing from the previous componentDidMount
and componentDidUpdate
APIs, this advice makes a lot of sense and it is engrained in me now. When using hooks and writing effects, I always reach for useEffect
first.
However, when developing livefromquarantine.club I found a case where it wasn’t obvious that I had to use useLayoutEffect
instead of useEffect
. I think my brain was holding on to ”useLayoutEffect
is for measuring stuff!” and not realizing there are other events that need to be synchronous.