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

RefObject vs MutableRefObject

Learn the difference between read-only RefObject and mutable MutableRefObject types.

RefObject vs MutableRefObject

What you'll learn: The critical difference between TypeScript's read-only RefObject and mutable MutableRefObject types, and when React gives you each one.

The Two Ref Types

When you use useRef in TypeScript, React returns one of two types depending on how you initialize it:

  • RefObject<T> – A read-only ref where you cannot reassign .current
  • MutableRefObject<T> – A mutable ref where you can freely change .current

Which One Do You Get?

The rule is simple:

// RefObject<HTMLDivElement> - read-only .current
const divRef = useRef<HTMLDivElement>(null);

// MutableRefObject<number> - mutable .current
const countRef = useRef<number>(0);

When you pass null as the initial value, TypeScript assumes you're creating a DOM ref that React will manage. It returns RefObject<T>, making .current read-only because React controls it.

When you pass any other value, TypeScript assumes you're managing the ref yourself for storing mutable data. It returns MutableRefObject<T>, letting you reassign .current freely.

Why It Matters

const divRef = useRef<HTMLDivElement>(null);
divRef.current = document.createElement('div'); // ❌ Error: read-only

const dataRef = useRef({ count: 0 });
dataRef.current = { count: 5 }; // ✅ Allowed: mutable

This distinction prevents you from accidentally overwriting DOM refs that React is managing, while still allowing you to use refs for storing arbitrary mutable data.

The Analogy

Think of RefObject like a display case with a lock—you can look through the glass (read .current), but only React has the key to change what's inside. MutableRefObject is an open box you control completely.

Key Takeaway: RefObject (from useRef(null)) protects DOM refs with read-only .current, while MutableRefObject (from any other initial value) gives you full mutation control for storing data across renders.