Sub topic 8
Typing useRef for DOM nodes and mutable values
This chapter assumes you know basic React hooks, TypeScript unions and generics, and the strict setup from the first chapter. It also assumes you can type useState.
useRef has two jobs. It holds a reference to a DOM element, and it holds a value that must survive re-renders without causing one. TypeScript treats these jobs differently, and the type you write for the initial value decides which one you get.
What a ref is
useRef(initial) returns one object that stays the same across renders. The object has a single property, current. Changing current does not trigger a re-render, and React does not track it.
Typing a ref means answering one question: what can current hold, and when?
- For a DOM ref,
currentisnulluntil React attaches the element after the first render. It becomesnullagain if the element is removed. - For a mutable value ref, you choose the type and the initial value.
Typing a ref to a DOM node
Pass the element type as the generic argument and null as the initial value.
import { useEffect, useRef } from "react";
export function SearchBox() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} type="search" />;
}Three things to notice:
- The generic names the element type that React will put in the ref, here
HTMLInputElement. inputRef.currentisHTMLInputElement | null, so you must check fornullbefore using it. Optional chaining (?.) is the usual way.- The
refprop on<input>only accepts a ref for an input. PassinginputRefto a<div>is a compile error, which catches copy-paste mistakes.
Use the most specific element type you can. HTMLButtonElement, HTMLFormElement, HTMLDivElement and HTMLCanvasElement each expose different methods. HTMLElement is a fallback when the element varies.
import { useRef } from "react";
export function Canvas() {
const canvasRef = useRef<HTMLCanvasElement>(null);
function draw() {
const canvas = canvasRef.current;
if (canvas === null) return;
const ctx = canvas.getContext("2d");
if (ctx === null) return;
ctx.fillRect(0, 0, 40, 40);
}
return (
<div>
<canvas ref={canvasRef} width={100} height={100} />
<button onClick={draw}>Draw</button>
</div>
);
}Here two null checks are needed. The first is because the ref may be empty. The second is because getContext can return null. Both are real runtime possibilities.
Why not use `!`?
You can write inputRef.current!.focus(). It compiles, but it hides the case where the element is not mounted, for example inside a conditional branch. Prefer a check, and use ! only where you can show the element exists.
Typing a ref for a mutable value
The same hook stores values that are not elements: timer IDs, the previous value of a prop, a flag that says "this ran already", or a WebSocket instance.
import { useEffect, useRef, useState, type ChangeEvent } from "react";
export function DebouncedInput({ onSettle }: { onSettle: (value: string) => void }) {
const [text, setText] = useState("");
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
function handleChange(e: ChangeEvent<HTMLInputElement>) {
const next = e.target.value;
setText(next);
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => onSettle(next), 300);
}
useEffect(() => {
return () => {
if (timerRef.current !== null) {
clearTimeout(timerRef.current);
}
};
}, []);
return <input value={text} onChange={handleChange} />;
}ReturnType<typeof setTimeout> is the safe way to type a timer ID. In a browser setTimeout returns a number. With Node typings loaded it returns a NodeJS.Timeout. Deriving the type from the function works in both cases.
The | null in the generic is what makes the ref writable. useRef<number | null>(null) says "this holds a number or nothing", and you may assign to current freely.
Refs without `null`
If the initial value is a real value, let inference work.
import { useRef } from "react";
export function ClickCounter() {
const clicks = useRef(0);
return (
<button
onClick={() => {
clicks.current += 1;
console.log(`Clicked ${clicks.current} times`);
}}
>
Click
</button>
);
}useRef(0) infers number. No generic is needed.
A reusable example: the previous value
import { useEffect, useRef } from "react";
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}The ref starts as undefined because there is no previous value on the first render. The return type says so, which forces callers to handle that case.
Choosing the generic: a decision guide
Version differences in `@types/react`
The meaning of useRef<T>(null) changed between versions of the type definitions. Check which one your project uses.
| Call | `@types/react` 18 | `@types/react` 19 | Column | Column | Column |
|---|---|---|---|---|---|
| `useRef<HTMLDivElement>(null)` | `RefObject<HTMLDivElement>`, `current` is read-only | `RefObject<HTMLDivElement \ | null>`, `current` is writable | ||
| `useRef<number \ | null>(null)` | `MutableRefObject<number \ | null>` | `RefObject<number \ | null>` |
| `useRef(0)` | `MutableRefObject<number>` | `RefObject<number>` | |||
| `useRef<number>()` with no argument | Allowed, `current` is `number \ | undefined` | Compile error, an argument is required |
If you see an error that a ref's current is a read-only property, you are on version 18 and the ref was created with null plus an element type. That is intentional: React owns DOM refs, so your code should not assign to them. If you really want a mutable ref that holds an element you manage yourself, write useRef<HTMLElement | null>(null).
Common errors
Writing to `current` during render
Reading or writing ref.current while the component function runs breaks the rule that rendering must be pure. TypeScript does not catch this. Do the reads and writes in event handlers and effects.
Expecting a re-render
Changing ref.current does not update the screen. If the UI must change, the value belongs in useState. A quick test: if the value appears in the JSX, it is state. If it only affects behavior, such as a timer ID, it can be a ref.
The element type does not match the tag
import { useRef } from "react";
export function Wrong() {
const ref = useRef<HTMLInputElement>(null);
// Error: HTMLInputElement is not assignable to HTMLDivElement
return <div ref={ref} />;
}Fix the generic to match the element. The error text is long, but the cause is always a mismatch between the tag and the type argument.
Forgetting the `null` in a mutable ref
On version 18 types, useRef<number>(null) produces a ref typed as a DOM-style, read-only RefObject<number>. Assigning to current fails. Write useRef<number | null>(null) when you intend to assign later.
Using the ref before the element exists
current is null during the first render and inside any code that runs before mount. An effect runs after mount, so it is a safe place to use a DOM ref. Rendering code is not.
Refs to child components
A ref on your own component does not reach the DOM node inside it unless the component forwards it. A later chapter covers typing forwarded refs. Until then, remember that ref on a function component you wrote is not an ordinary prop in React 18.
Exercise
You write const idRef = useRef<number>(null); to hold an interval ID, then assign idRef.current = window.setInterval(tick, 1000); inside an effect. On @types/react 18 this fails to compile. Why, and what is the fix?
Show answer
With version 18 types, passing null with a generic that does not include null selects the overload that returns a read-only RefObject<number>, so assigning to current is rejected. The fix is to include null in the type: useRef<number | null>(null). This returns a mutable ref. Check idRef.current !== null before calling clearInterval.
Exercise
A component renders <textarea ref={areaRef} />. Write the declaration of areaRef and a handler that clears the textarea's text safely.
Show answer
const areaRef = useRef<HTMLTextAreaElement>(null); and function clear() { if (areaRef.current !== null) { areaRef.current.value = ""; } }. The element type is HTMLTextAreaElement, and the null check is needed because the ref is empty until the element mounts.