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:
-
Accessing DOM Elements (The "React" way to avoid document.getElementById): When you pass a ref object to a React element as a
refattribute (e.g.,<input ref={myRef} />), React will automatically assign the actual DOM node tomyRef.current. This allows you to directly call DOM APIs like.focus(),.play(), or.scrollIntoView(). -
Holding Mutable State Without Triggering Renders: Unlike
useState, changing the.currentvalue 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
1import React, { useRef, useState, useEffect } from 'react';23export default function VideoPlayerAndTracker() {4 // 1. Ref for DOM Access5 const videoRef = useRef(null);67 // 2. Ref for tracking mutable data without rendering8 const playCountRef = useRef(0);910 const [isPlaying, setIsPlaying] = useState(false);1112 const handlePlayPause = () => {13 if (isPlaying) {14 videoRef.current.pause(); // Direct DOM manipulation15 setIsPlaying(false);16 } else {17 videoRef.current.play(); // Direct DOM manipulation18 setIsPlaying(true);1920 // Increment tracking counter silently without causing a re-render21 playCountRef.current += 1;22 console.log(`Video has been played ${playCountRef.current} times.`);23 }24 };2526 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 <video30 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 />3536 <div className="flex justify-between items-center">37 <button38 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>4344 <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.