This video is available to students only

useRef Hook

Learn about the useRef Hook, its use cases and implementation.

Hook: useRef#

The useRef Hook provides us with a way to store and retrieve a mutable (that is, subject to change) reference object. It has a .current property that can be initialized to a starting value. The object that’s returned from useRef will be persisted for the lifetime of the component, which is quite handy.

From the official React docs on useRef:

Essentially, useRef is like a “box” that can hold a mutable value in its .current property.

If you’ve come across the React.createRef function or seen those funny ref={} style attributes about the place, especially in class components, then the useRef Hook functions in a very similar way.

Use cases for useRef#

One of the most common use cases for the useRef Hook is to attach a reference to the underlying DOM element that a ref is assigned to. For our demo, we’re going to build a simple modal popup that, when closed, returns focus to the corresponding input element in a form.

We can use the useRef Hook to provide us with a way to access the input element in the React-generated DOM. With a reference to this element, we can access native properties and functions, such as the focus() function.

However, the useRef() Hook isn’t just for DOM refs. A ref object is a generic container with a mutable current property. This property can hold any value and is comparable to an instance property on a class.

Using the useRef Hook#

Using the useRef Hook couldn’t be simpler:

We call the useRef Hook, passing in a value of ‘null’ as an initial value (though this could be anything you want). In the return function, we define a standard HTML input element and assign our inputRef variable to the ref={} attribute. This essentially wires the underlying DOM input element into the useRef’s ‘current’ property, so that later on, in the handleSomething function, we can grab a reference to the input element.

In our case, we’ve gone with the common example of calling the focus() function to bring the browser focus into the input element.

Of course, if you want to change the value of the ref’s ‘current’ property, you can do so as you would with any JavaScript assignment — e.g. inputRef.current = ‘my value here’.

Building the useRef example#

With our fundamental knowledge of the Hook in place, let’s build something to showcase it in action! For this demo, we’ll be creating a form with a modal popup. Once the user clears the modal, we want to return focus to the correct area of the form, a specific input element.

Back in our project in VS Code, open up the styles.css file and add the following additional styles at the bottom: