Typing Mutable Value Refs
What you'll learn: How to type refs that hold any mutable value (not just DOM elements) without the awkward null union.
The Two Faces of useRef
You've learned that useRef<HTMLElement>(null) creates refs for DOM nodes, where null is essential because React assigns the element later. But refs have another superpower: storing any mutable value that persists across renders without triggering re-renders.
For these "value refs," you don't want null at all—you're managing the value directly.
The MutableRefObject Type
When you initialize useRef with a non-null value, TypeScript infers MutableRefObject<T>, which has a .current property you can read and write freely:
const countRef = useRef<number>(0);
// Type: MutableRefObject<number>
countRef.current += 1; // ✅ Always a number, never null
Compare this to DOM refs:
const inputRef = useRef<HTMLInputElement>(null);
// Type: RefObject<HTMLInputElement>
// .current is readonly and might be null
When to Use Mutable Value Refs
Perfect for tracking values that don't belong in state:
- Previous values for comparison
- Animation frame IDs
- Timer IDs
- Instance variables in function components
const previousValueRef = useRef<string>('');
useEffect(() => {
console.log(`Changed from ${previousValueRef.current} to ${currentValue}`);
previousValueRef.current = currentValue;
}, [currentValue]);
Key Takeaway: Type mutable value refs with useRef<T>(initialValue) where initialValue isn't null—you'll get MutableRefObject<T> with a freely writable .current property, avoiding the null checks needed for DOM refs.