Hello! Let's continue our journey into advanced React hooks.
In our last lesson, we built a powerful, scalable state management system by combining useReducer and useContext. This pattern allows us to manage complex state declaratively, letting React handle the "how" of updating the UI based on state changes.
However, there are times when we need to step outside of React's declarative world and issue direct, imperative commands. This is especially common when integrating with parts of the browser that aren't inherently "React-like," such as the DOM itself.
Today's lesson focuses on this "escape hatch." Our goal is to introduce the useRef hook to access DOM elements directly for imperative actions. You'll learn how to get a direct reference to a specific element in your JSX and call methods on it, enabling functionalities like managing focus, controlling media playback, or triggering animations.
What is a "Ref" and Why Is It Different from State?
At its core, useRef is a hook that lets you create a reference to a value that is not needed for rendering. The object it returns has a single property, current, which you can mutate directly.
The most critical difference between useRef and useState is this: updating a ref does not trigger a component re-render.
This makes refs perfect for two main scenarios:
- Storing mutable values that don't affect the visual output (like timer IDs or previous props).
- Holding a direct reference to a DOM node.
Today, we're focusing on the second use case.
To start, let's get a clear conceptual overview of useRef. This video does an excellent job of explaining what refs are, how they contrast with state, and why updating a ref doesn't cause a re-render.
Please watch from the beginning to 12:43. Pay close attention to the distinction between useState and useRef. The demonstration where a counter stored in a ref is incremented without the UI updating is a perfect illustration of the fundamental behavior of refs.
As the video demonstrates, if you try to display ref.current in your JSX, the UI won't update when you change the value. This is because React's rendering system doesn't "watch" refs for changes. A ref is like a private instance variable in a class—it persists for the lifetime of the component instance, but changing it doesn't trigger any lifecycle methods or re-renders.

Why Not Just Use document.querySelector?
Given your background in software engineering and JavaScript, you might wonder why we need a special hook for this. Why not just use standard DOM APIs like document.getElementById or document.querySelector?
While technically possible, doing so breaks React's core model and is considered a bad practice.
useRef Hook in React - Use Cases, Code Examples, ...
This article provides a concise explanation of why direct DOM manipulation is discouraged in a React application.
Please read the section titled 'Why Can't We Use the document Object to Access the DOM Directly?'. This will clarify the relationship between useRef and React's Virtual DOM.
To summarize the key points from the article:
- Bypassing the Virtual DOM: Direct manipulation can cause inconsistencies between React's representation of the UI (the Virtual DOM) and the actual DOM, leading to unpredictable bugs.
- Breaking Component Encapsulation: Components are no longer self-contained if they reach out and manipulate arbitrary parts of the DOM. This makes them brittle and hard to reuse.
- Conflicts with Rendering: React can re-render a component at any time. Any direct DOM modifications you've made could be wiped out during a re-render.
useRefintegrates into React's lifecycle, ensuring your reference is to the correct, currently rendered DOM node.
useRef is React's sanctioned way to work with the DOM imperatively.
The Core Pattern: Accessing a DOM Element
Using useRef to access a DOM element is a straightforward, two-step process. We'll use the classic example of focusing an input field.
useRef Hook in React - Use Cases, Code Examples, ...
The article we just looked at also provides a perfect, simple example of the DOM access pattern with TypeScript.
Read the sections 'Manipulating the DOM with useRef' and 'TypeScript with useRef Hook'. Notice the three key parts: creating the ref with useRef<HTMLInputElement>(null), attaching it via the ref attribute on the JSX element, and then accessing the DOM node through inputRef.current.
Let's break down the code from the article:
-
Create the Ref:
const inputRef = useRef<HTMLInputElement>(null);- We call
useRefwith an initial value ofnullbecause the DOM element doesn't exist yet when this code first runs. - We provide a TypeScript generic,
HTMLInputElement, to telluseRefwhat kind of element it will eventually hold. This gives us type safety and autocompletion oninputRef.current. The ref's type will beReact.RefObject<HTMLInputElement>.
- We call
-
Attach the Ref:
<input ref={inputRef} type="text" />- You pass the ref object to the special
refprop on any HTML JSX element. - When React renders this
<input>, it will assign the underlying DOM node to thecurrentproperty of ourinputRefobject.
- You pass the ref object to the special
-
Use the Ref:
const focusInput = () => { // The `?` is optional chaining, in case the ref is not yet attached. inputRef.current?.focus(); };- After the component has mounted,
inputRef.currentwill be the actual<input>element. - We can now call any standard DOM API method on it, like
.focus().
- After the component has mounted,
A More Practical Example: Controlling a Video Player
Managing media playback is a perfect use case for useRef. Actions like "play," "pause," or "seek" are imperative commands, not declarative state changes.
Let's build a simple video player component with custom controls.
import React, { useRef } from 'react';
const VideoPlayer = () => {
// 1. Create a ref to hold the video element
const videoRef = useRef<HTMLVideoElement>(null);
const handlePlay = () => {
// 3. Call DOM methods on the .current property
videoRef.current?.play();
};
const handlePause = () => {
videoRef.current?.pause();
};
const handleSeekForward = () => {
if (videoRef.current) {
videoRef.current.currentTime += 10;
}
};
return (
<div>
{/* 2. Attach the ref to the JSX element */}
<video
ref={videoRef}
width="400"
src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
/>
<div>
<button onClick={handlePlay}>Play</button>
<button onClick={handlePause}>Pause</button>
<button onClick={handleSeekForward}>+10s</button>
</div>
</div>
);
};
export default VideoPlayer;
In this example, clicking the "Play" button doesn't set a piece of state. It directly issues a command (play()) to the DOM node held by videoRef.current. This is the imperative escape hatch in action.
Test your understanding!
Imagine you modify the VideoPlayer component. You add a p tag to display the current playback time: <p>Current Time: {videoRef.current?.currentTime}</p>.
You notice that even though the video is playing and the currentTime property of the videoRef.current object is changing constantly, the number displayed in the <p> tag does not update. Why is that?
Show answer
The number doesn't update because changing a ref's .current property does not cause the component to re-render. The currentTime value is changing in the DOM element, but React has no reason to re-run the component's render function, so the JSX is never re-evaluated to display the new value.
To display a value that updates in real-time on the screen, you would need to store it in useState and update it using an event listener on the video element (e.g., the timeupdate event). This is a common pattern: you use refs for imperative control and state for declarative UI updates.
Why the .current Property?
Finally, let's briefly touch on a theoretical point that might appeal to your CS background. Why does useRef return an object { current: ... } instead of just the value itself?
useRef Hook in React - Use Cases, Code Examples, ...
The article we've been using has a great explanation for this design decision.
Please read the section 'Why Does useRef Have a current Property, and Why Can't We Store Data Directly?'. It explains the consistency and mutability management that this design enables.
In essence, useRef always gives you back the same object instance across re-renders. This object acts as a stable "box" or pointer. The contents of the box (the .current property) can change, but the box itself does not. This allows React to know that the ref itself is a stable dependency, while giving you a mutable value that you can freely modify without triggering rendering logic.
Conclusion
You've now learned about React's primary mechanism for dropping down into the DOM layer. While you should always prefer the declarative approach with state and props when possible, useRef is an indispensable tool for imperative tasks.
Key Takeaways:
useRefis React's "escape hatch" for interacting directly and imperatively with DOM elements.- Unlike
useState, updating a ref's.currentproperty does not trigger a component re-render. - The three-step pattern is:
- Create a ref with
useRef<ElementType>(null). - Attach it to a JSX element with the
ref={myRef}prop. - Access the DOM node via
myRef.currentin event handlers oruseEffecthooks.
- Create a ref with
- Direct DOM manipulation with
document.querySelectoris discouraged because it bypasses React's Virtual DOM and component model.
Preview of the Next Lesson:
Accessing DOM elements is the most common, but not the only, use for useRef. In our next lesson, we will explore its other primary function: using useRef to store mutable values that persist across renders without causing a re-render. This is perfect for managing things like interval IDs, tracking previous state, or caching expensive calculations.