Course contentsShow
← React
Lesson 703 of 2,39619. useRefFree lesson

Creating a Ref with useRef

Call useRef(initialValue) to create a ref object; the initial value is assigned to .current only once, on mount.

Creating a Ref with useRef

What you'll learn: How to call useRef() to create a ref object and understand when its initial value is assigned.

The Syntax

Now that you understand what a ref is (a mutable box that doesn't trigger re-renders), let's see how to actually create one.

You create a ref by calling useRef() and passing an initial value:

const myRef = useRef(initialValue);

This returns a ref object with a .current property. The initialValue you pass becomes myRef.current — but here's the crucial detail: this assignment only happens once, when the component first mounts.

Understanding the Initial Value

Think of useRef() like opening a safe deposit box at a bank. You can put something in it on day one (the initial value), and that thing stays there until you manually change it. The bank (React) doesn't reset the box's contents when you visit again (re-render).

function Timer() {
  const countRef = useRef(0); // countRef.current = 0 on mount
  
  // On subsequent re-renders, countRef.current 
  // keeps whatever value it had before
}

Unlike useState, calling useRef() again during re-renders doesn't reset .current. The initial value is used only the first time.

Common Initial Values

const numberRef = useRef(0);
const stringRef = useRef('');
const nullRef = useRef(null); // Very common for DOM references
const objectRef = useRef({ count: 0 });

Key Takeaway: Call useRef(initialValue) to create a ref object; the initial value is assigned to .current only once on mount, and React never touches it again — all changes after that are your responsibility.