Course contentsShow
← React
Lesson 723 of 2,39619. useRefFree lesson

Video and Audio Control with Refs

Using refs to call play(), pause(), and other media methods on video and audio elements.

Video and Audio Control with Refs

You'll learn how to control video and audio playback using refs to directly call media methods.

Why Refs for Media Control?

Video and audio elements have built-in methods like play(), pause(), muted, and properties like currentTime that you need to control programmatically. These aren't state changes in your React component—they're direct commands to the browser's media player. Refs give you the handle to issue those commands.

Think of it like having a remote control for your TV. You don't need to track whether the TV is playing or paused in your component's state—you just need the remote (the ref) to press play or pause when the user clicks a button.

The Basic Pattern

function VideoPlayer() {
  const videoRef = useRef(null);

  function handlePlay() {
    videoRef.current.play();
  }

  function handlePause() {
    videoRef.current.pause();
  }

  return (
    <div>
      <video ref={videoRef} src="/video.mp4" />
      <button onClick={handlePlay}>Play</button>
      <button onClick={handlePause}>Pause</button>
    </div>
  );
}

The ref gives you direct access to the actual DOM <video> element, so you can call browser-native methods on it.

Audio Works the Same Way

function AudioPlayer() {
  const audioRef = useRef(null);

  function toggleMute() {
    audioRef.current.muted = !audioRef.current.muted;
  }

  return (
    <div>
      <audio ref={audioRef} src="/song.mp3" />
      <button onClick={toggleMute}>Toggle Mute</button>
    </div>
  );
}

Key Takeaway: Use refs to control video and audio elements by calling their native methods (play(), pause()) and setting properties (muted, currentTime) directly—no state needed for the actual playback control.