Video pausing unexpectedly when video `onTimeUpdate` event is called (with React Hooks)

Viewed 472

CODE

This is the video element:

    <video
      ref={videoRef}
      onDurationChange={onSetVideoDuration}
      onTimeUpdate={onSetVideoTimestamp}
      width="100%"
      controls
    >

The function onSetVideoTimestamp is the one used to set the video timestamp state when changes:

  const onSetVideoTimestamp = (event: SyntheticEvent<HTMLVideoElement, Event>) => {
    const timestamp = event.currentTarget.currentTime
    setVideoTimestamp(Math.floor(timestamp))
  }

and this is how videoTimestamp and setVideoTimestamp are declared:

const [videoTimestamp, setVideoTimestamp] = useState(0)

WHAT IS WORKING

Basically, the above code works, which means the timestamp state is correctly set.

THE PROBLEM

  • The problem is that the timestamp state is constantly updated since the video is playing and it is causing the video to always pausing and unpausing. The video reproduction in conclusion is not fluid.

  • Another issue is that if I set to update the state every 60 seconds, with this code:

  const onSetVideoTimestamp = (event: SyntheticEvent<HTMLVideoElement, Event>) => {
    if(event.currentTarget.currentTime > videoTimestamp + 60) {
       const timestamp = event.currentTarget.currentTime
       setVideoTimestamp(Math.floor(timestamp))
    }
  }

STILL the video pauses and unpauses - in that single moment - after 60 seconds of video are played.

1 Answers

A component rerenders if the state was updated. And you update the state of your component constantly. That's why your video is playing not fluid. You should avoid to update it so often. A solution is to use currentTime of video to get the current time:

const currentTime = htmlMediaElement.currentTime;
htmlMediaElement.currentTime = 35;

To get access to video you can use useRef.

Related