Next.js Discord

Discord Forum

state and intersection observer in use effect running only on mount

Unanswered
Rose-breasted Grosbeak posted this in #help-forum
Open in Discord
Rose-breasted GrosbeakOP
I have a simple video element that I want to paused/played whenever it is visible, until the user paused it manually.

I don't want to add the state in the dependency array, because the observer shouldn't be created repeatedly. What are my options?

 const Video = () => {
  //   const [isPlaying, setIsPlaying] = useState(false);
  const [pausedManually, setPausedManually] = useState(false);
  const videoRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        const target = entry.target as HTMLVideoElement;

        console.log("observer", { pausedManually });
        if (entry.intersectionRatio === 1 && !pausedManually) {
          //   target.play();
        } else if (!entry.isIntersecting) {
          //   target.pause();
        }
      },
      {
        threshold: [1, 0],
      },
    );
    if (videoRef.current) {
      observer.observe(videoRef.current);
    }

    return () => {
      console.log("use eff returned");
      observer.disconnect();
    };
  }, []);

  return (
    <div
      style={{
        height: "200px",
        background: "red",
        color: "white",
        margin: '100vh 0',
      }}
      ref={videoRef}
      onClick={() => {
        setPausedManually((p) => !p);
      }}
    >
      <pre>{JSON.stringify({ pausedManually }, null, 2)}</pre>
    </div>
  );
}

0 Replies