Skip to main content
Albero Academy

Refs & the DOM

Reach outside React's declarative model when you must — useRef for DOM access and mutable values, plus forwarding refs.

Chapter 9React14 min readBeginner friendly
  • #React
  • #useRef
  • #DOM

React is declarative — you describe state and it updates the DOM. Occasionally you need an escape hatch to touch a DOM node directly (focus an input, measure an element, play a video) or to hold a value that survives re-renders without triggering one. useRef is that hatch.

Why refs?

A ref is a container with a .current property that persists across renders and, crucially, changing it does not cause a re-render. That makes it right for two jobs: referencing DOM nodes and storing mutable values that aren't part of the UI.

Accessing a DOM node

focus an input
import { useRef, useEffect } from "react";
function SearchBox() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // focus on mount
}, []);
return <input ref={inputRef} />;
}

Mutable values

Use a ref to remember something between renders without re-rendering — a timer id, the previous value, a flag:

a ref that isn't UI
function Timer() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
const start = () => {
intervalRef.current = setInterval(() => setSeconds(s => s + 1), 1000);
};
const stop = () => clearInterval(intervalRef.current);
// intervalRef survives re-renders; updating it doesn't trigger one.
}

Forwarding refs

A parent can't put a ref on a custom component and reach its inner DOM node by default. forwardRef passes a ref through to a child element — how reusable input components expose focus:

forwardRef
import { forwardRef } from "react";
const Input = forwardRef((props, ref) => (
<input ref={ref} className="input" {...props} />
));
// Now a parent can do <Input ref={myRef} /> and focus it.

Practice

Build a search box that focuses on mount with useRef + useEffect. Add a start/stop stopwatch that keeps its interval id in a ref. Then make a reusable Input with forwardRef and focus it from a parent button.

Key takeaways

  1. 01useRef holds a .current value that persists across renders and does NOT trigger a re-render when changed.
  2. 02Attach a ref to an element to access its DOM node (focus, measure, play).
  3. 03Use refs for mutable behind-the-scenes values (timer ids, previous values) — not UI data.
  4. 04If changing a value should update the screen, use state, not a ref.
  5. 05forwardRef passes a ref through a custom component to an inner element.