Search code examples
javascriptreactjscreate-react-appintervalsreact-hooks

Interval inside React useEffect - store it in a useRef Hook to preserve value overtime warning


So I have this method:

useEffect(() => {
    //.. other logic here

    // Firefox doesn't support looping video, so we emulate it this way
    video.addEventListener(
      "ended",
      function() {
        video.play();
      },
      false
    );
  }, [videoWidth, videoHeight]);

Now it throws an error where it says:

Assignments to the 'interval' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.

I am confused on what does this mean? especially this part: To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property.


Solution

  • The error is pointing you to the right direction. Use the useRef hook to reference the video element. Since the handleVideo function makes the dependencies of useEffect Hook change on every render we wrap the handleVideo definition into its own useCallback() Hook.

    import React, { useEffect, useRef, useCallback } from "react";
    
    function Video() {
      const videoRef = useRef(null);
    
      const handleVideo = useCallback(() => {
        videoRef.current.play()
      }, [])
    
      useEffect(() => {
        const video = videoRef.current
        video.addEventListener('ended', handleVideo)
    
        return () => {
          video.removeEventListener('ended', handleVideo)
        }
      }, [handleVideo])
    
    
    
      return <video width="400" controls ref={videoRef} src="https://www.w3schools.com/html/mov_bbb.mp4" />
    }