Typing useRef for DOM Elements and Mutable Values
What you'll learn: How to distinguish between RefObject (for DOM refs) and MutableRefObject (for mutable containers) when using useRef in React with TypeScript.
Two Faces of useRef
The useRef hook in React serves two distinct purposes, and TypeScript expresses this through two different return types:
- RefObject: For DOM element references (read-only
.current) - MutableRefObject: For mutable value containers (writable
.current)
Think of RefObject like a safety-sealed viewing window—you can look through it, but React controls what's on the other side. MutableRefObject is like a storage box you fully control.
RefObject for DOM Elements
When you pass null as the initial value and specify a DOM element type, TypeScript returns a RefObject:
const inputRef = useRef<HTMLInputElement>(null);
// Type: RefObject<HTMLInputElement>
// inputRef.current is HTMLInputElement | null
The .current property here is read-only. React manages the reference lifecycle—you shouldn't manually assign to it. This models the DOM ref pattern correctly.
MutableRefObject for Mutable Values
When you pass a non-null initial value, TypeScript returns a MutableRefObject:
const countRef = useRef<number>(0);
// Type: MutableRefObject<number>
// countRef.current is number (always accessible)
Here .current is fully mutable—you can read and write freely. This is perfect for values that need to persist across renders without causing re-renders.
When to Use Which
Use RefObject (pass null initially) when connecting to JSX elements. Use MutableRefObject (pass an actual value) when storing mutable data like timers, previous values, or any state that shouldn't trigger re-renders.
Key Takeaway: TypeScript distinguishes RefObject<T> (read-only .current, for DOM refs initialized with null) from MutableRefObject<T> (writable .current, for mutable containers initialized with values), ensuring you use refs safely based on their purpose.