DEV Community

Discussion on: How to use async function in useEffect?

 
hbgl profile image
hbgl

Thanks for sharing this very interesting talk. Using the loader api from react-router should definitely be preferred over fetching in the useEffect hook. But I still don't buy the full 'you shouldn't be using async in useEffect' thing because I don't see the fundamental difference between a sync and async effect. An effect is an effect is an effect. I mean look at the VideoPlayer example from the page you linked:

import { useEffect, useRef } from 'react';

function VideoPlayer({ src, isPlaying }) {
  const ref = useRef(null);

  useEffect(() => {
    if (isPlaying) {
      ref.current.play();
    } else {
      ref.current.pause();
    }
  });

  return <video ref={ref} src={src} loop playsInline />;
}
Enter fullscreen mode Exit fullscreen mode

HTMLMediaElement.play() returns a Promise. Why would it be wrong to make the effect async and await the video being played? React surely doesn't "yell" at you as long you do the proper cleanup.

Thread Thread
 
brense profile image
Rense Bakker

You can use async side effects but you would have to use React suspense. Using async side effects without React suspense is an antipattern and should be avoided because A. it makes your app really difficult to debug and B. it has the potential to cause an infinite render loop.