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

The null Initial Value Pattern

Understand why DOM refs must start as null and how to handle the null | T union type safely.

The null Initial Value Pattern

You'll learn: Why DOM refs must start as null and how to safely handle TypeScript's null | T union type.

Why Refs Start as null

When you create a ref for a DOM element, you have a timing problem: the ref exists before the component renders, but the actual DOM node doesn't exist until after the JSX has been mounted. This means your ref can't point to the element immediately—it must start as null.

const buttonRef = useRef<HTMLButtonElement>(null);

That null isn't optional—it's required because React hasn't created the DOM element yet. The ref starts empty, and React fills it in after the first render.

The Union Type Challenge

TypeScript sees buttonRef.current as HTMLButtonElement | null. This union reflects reality: sometimes the element exists, sometimes it doesn't (like before mounting or after unmounting).

// ❌ TypeScript error: Object is possibly 'null'
buttonRef.current.focus();

// ✅ Safe with null check
if (buttonRef.current) {
  buttonRef.current.focus();
}

// ✅ Safe with optional chaining
buttonRef.current?.focus();

When to Handle Null

Always check for null when accessing the ref, especially in:

  • Event handlers (element might be unmounted)
  • useEffect (timing matters)
  • Conditional rendering scenarios

Think of the ref like a parking space: it exists before the car (DOM element) arrives, and it's empty (null) until React "parks" the element there.

Key Takeaway: DOM refs must initialize with null because elements don't exist yet at creation time—always handle the null | T union with null checks or optional chaining before accessing ref properties.