React, is there a way to play sound on useEffect?

Viewed 1164

I installed use-sound,

const [ play ] = useSound(sound, {interrupt: true})

then I want to play a sound when theres a data change

useEffect(() => {
    if (prevData.length < newData.length) {
      play()
    }
  }, [ prevData,newData ])

It's pretty strange cause sometimes it works.. More often locally than online..

Actually i'd like to play the sound even if the window is not in focus. And in this case, again sometimes it works..

But I can't figure why this is not stable since the setup is pretty simple.

1 Answers

i thinks would be better if u make seperate component just for sound like this: sandbox.

import { useEffect } from "react";
import useSound from "use-sound";
import beep from "./beep-08b.mp3";

export default function Sound({ counter }) {
  const [play] = useSound(beep, { interrupt: true });

  useEffect(() => {
    play();
  }, [counter, play]);
  return null;
}
Related