Refs and the DOM in React
Introduction
So far, you have learned how React manages UI using state and props. Normally, React handles updates automatically through its virtual DOM system. However, sometimes you need to directly interact with a DOM element — for example, focusing an input field, playing a video, or measuring an element’s size.
For these cases, React provides refs (short for references). Refs give you a way to access DOM elements directly within React components.
What Is a Ref?
A ref is a special object in React that provides a reference to a DOM element or a React component instance. Refs allow you to perform actions that cannot be easily handled through state or props.
Common use cases include:
Focusing an input field
Triggering animations
Managing media playback
Measuring element dimensions
Creating a Ref with useRef
In functional components, refs are created using the useRef hook.
import { useRef } from "react";
function InputFocus() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
Here, inputRef.current points to the actual DOM input element.
How useRef Works
The useRef hook returns an object with a single property: current. This property holds the DOM element after the component renders.
Updating a ref does not cause a re-render. This makes refs useful for storing values that do not affect UI rendering.
Using Refs with useEffect
Refs are often used together with useEffect when you need to interact with the DOM after rendering.
import { useEffect, useRef } from "react";
function AutoFocus() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
The input automatically receives focus when the component mounts.
Refs vs State
Refs and state serve different purposes:
State triggers re-renders when updated
Refs store values without causing re-renders
Use state for data that affects UI and refs for direct DOM interactions.
Forwarding Refs
Sometimes you need to pass a ref to a child component. React provides forwardRef for this.
import React, { forwardRef } from "react";
const CustomInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
Now the parent component can control the child’s input element.
Common Mistakes to Avoid
Overusing refs instead of state
Trying to modify DOM directly without React control
Forgetting that ref updates do not trigger re-renders
Summary
In this chapter, you learned how refs allow direct interaction with DOM elements in React. You used useRef to create references, combined refs with useEffect, understood the difference between refs and state, and learned about forwarding refs. Refs are powerful tools when you need DOM-level control beyond React’s normal rendering flow.