Course contentsShow
← React
Lesson 2383 of 2,39651. TypeScript with React BasicsFree lesson

Typing useRef: Mutable Values vs DOM Refs

Understand the difference between useRef<T> for mutable values and useRef<HTMLElement | null> for DOM refs.

Typing useRef: Mutable Values vs DOM Refs

You'll learn how useRef requires different TypeScript annotations depending on whether you're storing DOM references or mutable values.

The Two Faces of useRef

useRef serves two distinct purposes in React, and TypeScript treats them differently:

  1. DOM Refs: When you attach a ref to a JSX element to access the DOM node
  2. Mutable Values: When you need a "box" to hold a value that persists across renders without causing re-renders

DOM Refs: The Null Pattern

When referencing DOM elements, you specify the element type and initialize with null:

const inputRef = useRef<HTMLInputElement>(null);

// Later in JSX:
<input ref={inputRef} />

// TypeScript knows this might be null
if (inputRef.current) {
  inputRef.current.focus();
}

TypeScript infers RefObject<HTMLInputElement>, where .current is read-only and starts as null.

Mutable Values: Skip the Null

For storing mutable values that aren't DOM nodes, provide an initial value directly:

const countRef = useRef<number>(0);

// TypeScript infers MutableRefObject<number>
countRef.current += 1; // ✅ Writable, never null

You can also store objects, timers, or any value:

const timerRef = useRef<NodeJS.Timeout | null>(null);
const previousValueRef = useRef<string>('');

The Key Difference

Think of DOM refs as "read-only pointers" (React manages the value) and mutable value refs as "persistent variables" (you manage the value). The type system enforces this: RefObject has readonly .current, while MutableRefObject allows direct assignment.

Key Takeaway: Use useRef<HTMLElement>(null) for DOM refs (read-only, nullable), and useRef<T>(initialValue) for mutable values (writable, your initial type).