What is useRef and what are its two main use cases?

useRef is a hook that returns a mutable object with a .current property. The value in .current is preserved across re-renders.

The Two Main Superpowers of useRef:

  1. Accessing DOM Elements (The "React" way to avoid document.getElementById): When you pass a ref object to a React element as a ref attribute (e.g., <input ref={myRef} />), React will automatically assign the actual DOM node to myRef.current. This allows you to directly call DOM APIs like .focus(), .play(), or .scrollIntoView().

  2. Holding Mutable State Without Triggering Renders: Unlike useState, changing the .current value of a ref does not cause the component to re-render. This makes it perfect for storing background data, tracking timeouts/intervals, or keeping track of how many times a component has rendered without causing an infinite loop.

Code example

tsx
1import React, { useRef, useState, useEffect } from 'react';
2
3export default function VideoPlayerAndTracker() {
4 // 1. Ref for DOM Access
5 const videoRef = useRef(null);
6
7 // 2. Ref for tracking mutable data without rendering
8 const playCountRef = useRef(0);
9
10 const [isPlaying, setIsPlaying] = useState(false);
11
12 const handlePlayPause = () => {
13 if (isPlaying) {
14 videoRef.current.pause(); // Direct DOM manipulation
15 setIsPlaying(false);
16 } else {
17 videoRef.current.play(); // Direct DOM manipulation
18 setIsPlaying(true);
19
20 // Increment tracking counter silently without causing a re-render
21 playCountRef.current += 1;
22 console.log(`Video has been played ${playCountRef.current} times.`);
23 }
24 };
25
26 return (
27 <div className="max-w-md mx-auto p-6 bg-white rounded-xl shadow-lg">
28 {/* Attach the ref to the DOM element */}
29 <video
30 ref={videoRef}
31 className="w-full rounded-lg mb-4 bg-black"
32 src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
33 onEnded={() => setIsPlaying(false)}
34 />
35
36 <div className="flex justify-between items-center">
37 <button
38 onClick={handlePlayPause}
39 className="px-6 py-2 bg-indigo-600 text-white rounded-full font-bold hover:bg-indigo-700 transition"
40 >
41 {isPlaying ? 'Pause' : 'Play Video'}
42 </button>
43
44 <p className="text-gray-500 text-sm">
45 Play clicks: {playCountRef.current}
46 </p>
47 </div>
48 </div>
49 );
50}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.

Open in study app