Sub topic 4
Getting a Handle on a DOM Element
This chapter assumes you know JavaScript closures, React function components and JSX, useState, and basic useEffect. You should also know what a DOM element is, and what focus and scrolling mean in a browser.
React normally manages the DOM for you. You describe the UI with JSX, and React updates the page. Sometimes you need the actual browser element, for example to focus an input, play a video, or measure a box. A ref gives you that handle.
Attaching a ref to an element
Pass a ref object to the ref attribute of a built-in element such as <input> or <div>. React stores the matching DOM node in the ref's current property.
import { useRef } from 'react';
export function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</>
);
}The sequence is:
useRef(null)returns an object{ current: null }.- React renders the component and creates the
<input>DOM node. - During the commit step, React sets
inputRef.currentto that node. - The click handler runs later and reads
inputRef.current, which is now the real element.
The ref object has the same identity on every render, so you can safely use it in handlers and effects without listing it as a changing value.
What the node is
inputRef.current is a plain browser object. For an <input>, it is an HTMLInputElement. You can use any standard DOM API on it:
| Element | Type of `current` | Common uses |
|---|---|---|
| `<input>`, `<textarea>` | `HTMLInputElement`, `HTMLTextAreaElement` | `focus()`, `select()`, `setSelectionRange()` |
| `<div>`, `<section>` | `HTMLDivElement`, `HTMLElement` | `scrollIntoView()`, `getBoundingClientRect()` |
| `<video>`, `<audio>` | `HTMLVideoElement`, `HTMLAudioElement` | `play()`, `pause()` |
| `<canvas>` | `HTMLCanvasElement` | `getContext('2d')` |
| `<dialog>` | `HTMLDialogElement` | `showModal()`, `close()` |
When the ref is null
A ref is null in two situations:
- Before the first commit. While the component function runs for the first time, the element does not exist yet.
- After the element is removed. React sets
currentback tonullwhen the element unmounts. The same happens if the element is never rendered, such as when a condition is false.
This is why code like the following fails on the first render:
import { useRef } from 'react';
export function Broken() {
const inputRef = useRef(null);
// Runs during render: inputRef.current is still null here.
inputRef.current.focus(); // TypeError: Cannot read properties of null
return <input ref={inputRef} />;
}Read ref.current in event handlers or in effects. By the time those run, the commit has finished and the node is set.
Using a ref in an effect
An effect runs after the commit, so the node is available. This focuses an input when the component first appears:
import { useEffect, useRef } from 'react';
export function AutoFocusField() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} placeholder="Type here" />;
}For a plain focus on mount, the autoFocus attribute is simpler. The effect form is useful when focus depends on logic, such as focusing only after data has loaded.
If the element is conditional, guard the access:
import { useEffect, useRef, useState } from 'react';
export function EditableTitle({ title }) {
const [editing, setEditing] = useState(false);
const inputRef = useRef(null);
useEffect(() => {
if (editing && inputRef.current) {
inputRef.current.select();
}
}, [editing]);
return editing ? (
<input ref={inputRef} defaultValue={title} onBlur={() => setEditing(false)} />
) : (
<button onClick={() => setEditing(true)}>{title}</button>
);
}When editing is false, no input exists and inputRef.current is null. After the click, React renders the input, sets the ref, and then the effect selects its text.
One ref, one element
A ref object holds one value. If you attach the same ref to two elements, the last one React attaches wins.
import { useRef } from 'react';
export function Wrong() {
const ref = useRef(null);
return (
<>
<input ref={ref} />
<input ref={ref} /> {/* ref.current points here only */}
</>
);
}For two elements, create two refs. For a variable number of elements, such as items in a list, you can't call useRef in a loop. Hooks must be called in the same order on every render, never inside loops. Use a callback ref that stores nodes in a collection instead. A later chapter covers that pattern.
Refs on components
Refs work on built-in elements by default. If you write <MyInput ref={ref} /> and MyInput is your own component, the ref does not reach the DOM unless the component passes it on. React 19 lets function components receive ref as a regular prop. Earlier versions use forwardRef. Without that, older React versions warn and ref.current stays null. Passing refs to children is covered in its own chapter.
Refs and the render phase
Treat ref.current for a DOM node as read-only information that React manages. Your code can read it in handlers and effects and call methods on the node. Don't assign to ref.current yourself for DOM refs. React owns that value.
You also shouldn't use a ref to change what the user sees when React can do it for you. Consider this:
import { useRef } from 'react';
export function Counter() {
const labelRef = useRef(null);
const countRef = useRef(0);
function handleClick() {
countRef.current += 1;
labelRef.current.textContent = `Clicked ${countRef.current} times`;
}
return (
<>
<p ref={labelRef}>Clicked 0 times</p>
<button onClick={handleClick}>Click</button>
</>
);
}This works, but it bypasses React. If the component re-renders for another reason, React may overwrite the text. Use state for data that appears on screen.
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>Clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click</button>
</>
);
}A safe rule: use refs to call methods that React has no declarative form for, such as focus(), scrollIntoView(), play(), or measuring. Don't use them to add, remove, or edit the children and text of nodes that React renders. React can lose track of those changes and throw errors when it later tries to update or remove the nodes.
Common mistakes
- Reading
ref.currentduring render. It isnullon the first render. Move the read into a handler or an effect. - Forgetting the null check. In conditional UI,
currentmay benull. Use a guard or optional chaining, such asref.current?.focus(). - Attaching one ref to many elements. Only the last element is kept. Use a callback ref with a
Mapfor lists. - Passing
refto your own component and expecting a node. The component must forward the ref. - Editing React-managed DOM by hand. Calls like
appendChildorremoveon rendered nodes can break React's bookkeeping. - Using
refwhere a prop was meant. On a plain function component in React versions before 19,refis not passed inprops.
Exercise
A component has const boxRef = useRef(null); and calls console.log(boxRef.current.offsetHeight) directly in the function body, above the return. The <div ref={boxRef}> is rendered unconditionally. What happens on the first render, and where should the measurement code move?
Show answer
On the first render the div has not been created yet, so boxRef.current is null and reading offsetHeight throws a TypeError. Move the code into a useEffect (or an event handler). Effects run after React commits the DOM, when boxRef.current holds the div. Guard with if (boxRef.current) if the element can be absent.
Exercise
You need to focus a text field inside a form that is only shown after a user clicks "Add note". Which hook calls do you need, and why is useRef alone not enough to do it right after the click?
Show answer
Create the ref with useRef(null) and put it on the input. Set a state value such as showForm in the click handler. The input does not exist until React re-renders and commits, so calling ref.current.focus() in the same handler would hit null. Use useEffect with [showForm] as its dependency, and call inputRef.current?.focus() when showForm is true.