Course contentsShow
← React
Lesson 491 of 2,39614. Uncontrolled ComponentsFree lesson

Creating a Ref with useRef

Initialize a ref with useRef(null) to store a mutable reference to a DOM element without triggering re-renders.

Creating a Ref with useRef

What you'll learn: How to initialize a ref using useRef(null) to hold a reference to a DOM element without causing re-renders.

The Core Idea

In the previous lesson, you learned what uncontrolled components are—form inputs where the DOM itself maintains the current value. But how do you actually access that DOM element from your React code when you need the value?

This is where refs come in. A ref is like a persistent container that holds a reference to something—usually a DOM element—that survives across re-renders but doesn't trigger re-renders when it changes.

You create a ref using the useRef hook:

import { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);
  
  // inputRef.current will eventually point to the actual DOM input element
}

The null argument is the initial value. You start with null because the DOM element doesn't exist yet during the first render—React needs to create it first.

Think of It Like a Box

Imagine useRef creates a special box with a .current property inside. You can put anything in that box, and it will stay there between renders. Unlike state, changing what's in the box doesn't tell React to re-render your component.

For uncontrolled inputs, you'll "put" the DOM element reference into this box so you can access it later (like when a form is submitted).

Key Takeaway: useRef(null) creates a mutable reference container that persists across renders without triggering re-renders—perfect for storing DOM element references in uncontrolled components.