Sub topic 8
Typing useRef for DOM nodes and mutable values
This chapter assumes you know useState and useEffect, and that your project already compiles TSX in strict mode. useRef serves two jobs, and TypeScript treats them differently. One is holding a DOM element. The other is holding a value that can change without causing a re-render.
Refs that point to DOM nodes
Pass the element type as the type argument and null as the initial value:
import { useRef } from "react";
export function SearchBox() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<div>
<input ref={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus</button>
</div>
);
}React sets current to the element after the first render. Before that, and after the element unmounts, current is null. The type reflects this, so strict mode forces you to handle null. Use optional chaining (?.) as above, or an explicit if (inputRef.current) check.
Pick the most specific element type. HTMLInputElement, HTMLButtonElement, HTMLDivElement, and HTMLCanvasElement each expose different methods. A ref typed as HTMLElement does not have focus on inputs' value, and one typed as HTMLInputElement cannot be attached to a <div>.
Refs that hold mutable values
A ref can also store anything you want to keep between renders, such as a timer ID, a previous value, or a flag. Changing current does not trigger a re-render. When the stored value starts as null and later holds something else, include null in the type argument:
import { useEffect, useRef, useState } from "react";
export function Ticker() {
const [seconds, setSeconds] = useState(0);
const [running, setRunning] = useState(false);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
function start() {
if (intervalRef.current !== null) return;
intervalRef.current = setInterval(() => setSeconds((s) => s + 1), 1000);
setRunning(true);
}
function stop() {
if (intervalRef.current === null) return;
clearInterval(intervalRef.current);
intervalRef.current = null;
setRunning(false);
}
useEffect(() => {
return () => {
if (intervalRef.current !== null) clearInterval(intervalRef.current);
};
}, []);
return (
<button onClick={running ? stop : start}>
{running ? "Stop" : "Start"} ({seconds}s)
</button>
);
}ReturnType<typeof setInterval> is used because the return type differs between browser typings (number) and Node typings (NodeJS.Timeout). This form works with either.
Why the type argument decides what you get
The two uses differ in the type argument you write.
| Call | Meaning | Column |
|---|---|---|
| `useRef<HTMLInputElement>(null)` | A DOM ref. React fills in `current`. | |
| `useRef<number \ | null>(null)` | A mutable value you assign yourself. |
| `useRef(0)` | A mutable `number`, inferred from the initial value. |
In React 18 typings, useRef<HTMLInputElement>(null) returns a RefObject whose current is read-only. This is intentional, because React owns that field. If you write useRef<number | null>(null), null is part of T, so you get a mutable MutableRefObject and can assign to current. In React 19 typings, both cases return a RefObject with a writable current, and useRef requires an initial argument. The code in this chapter compiles under both.
Common errors
Object is possibly null: you usedref.current.focus()without a check. Add?.or anif.Cannot assign to 'current' because it is a read-only property: you gave a DOM-style ref (nullinitial value,Twithoutnull) a value to hold. Add| nullto the type argument.Type 'RefObject<HTMLDivElement>' is not assignable to type 'LegacyRef<HTMLInputElement>': the element type does not match the JSX tag. Change the type argument.- Reading
ref.currentduring render: the type allows it, but the value is not set on the first render. Read refs in event handlers and effects.
Exercise
You want to remember the previous value of a count: number prop between renders, without causing extra renders. Write the useRef declaration, and say whether previous.current needs a null check.
Show answer
const previous = useRef<number | null>(null); The | null is needed because there is no previous value on the first render, and it makes current writable. Yes, you must handle null before using the value, for example previous.current ?? 0. Update it inside useEffect(() => { previous.current = count; }, [count]);.