Problem Solved

React + TS · useRef type

Home › Courses › React › Problems › useRef type
⚛️ Problem · 5 min read

How to type useRef.
DOM refs vs mutable refs.

useRef has two completely different uses — pointing at a DOM element, and storing a mutable value that survives renders. Both use the same hook, but the types are different. Get the generic wrong and TypeScript fights you. Get it right and refs are some of the cleanest code in React.

Short answer: Two patterns. DOM ref: useRef(null) — element type, null initial value, access via ref.current?.focus();. Mutable value: useRef(0) — value type, actual initial value, access via ref.current. In both cases, the generic is the type of .current. Never type it as any or RefObject — you'll lose every method on the element.

✅ Solution 1 — DOM refs

The pattern for accessing a real element.

A DOM ref points to a real element in the browser. The generic is the element type (HTMLInputElement, HTMLDivElement, HTMLButtonElement), and the initial value is null — because the element doesn't exist until React attaches it after render.

dom-ref.tsx
import { useRef } from 'react';

function FocusDemo() {
// ─── The canonical DOM ref ───────────────────
const inputRef = useRef(null);
// inputRef.current: HTMLInputElement | null

function focus() {
// Narrow with ?. — ref might not be attached yet
inputRef.current?.focus();
// inputRef.current.select(); // ❌ possibly null
}

function clear() {
if (inputRef.current) {
inputRef.current.value = ''; // ✅ narrowed by if
inputRef.current.focus();
}
}

return (
"Type here..." />
); } // ─── Other element types ───────────────────── function ManyRefs() { const divRef = useRef(null); const buttonRef = useRef(null); const videoRef = useRef(null); const canvasRef = useRef(null); const formRef = useRef(null); return (
); } // ─── Common DOM element types ───────────────── // // HTMLInputElement — // HTMLTextAreaElement —