Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Understanding useRef

An intro to refs and React Hooks

4 min readJul 12, 2020

--

Press enter or click to view image in full size
Photo by Nathan Shively on Unsplash

The useRef is an out-of-the-box hook in React 16.8. It is the functional component alternative to createRef() that is used in React’s class (stateful) components. Whether or not you are familiar with refs, createRef, or useRef, this article will guide you through the basics of getting started with this quite useful hook.

First off, there are two main uses for the useRef hook in a React functional component: accessing a DOM element and storing mutable information in the state without triggering a re-render of that component. We will take a look at an example of both of these and discuss some things to keep in mind along the way.

A note of caution

Generally, we should avoid using the useRef in React for anything that can be done declaratively — that is, we should let React handle the state of the app and the “how” of each component as much as possible. However, there are some situations where you need to imperatively alter or interact with a DOM element, telling it “how” to treat (or not treat) something, and therefore bypassing the state. Some common DOM element examples of this include managing focus on a particular element, selecting text, or media playback. We’ll also explore a few other reasons we may need to get imperative with React.

What is a ref?

In React, a ref is an attribute that can be used in either element tags or component tags themselves. A ref provides “a way to access DOM nodes or React elements created in the render method,” (Refs and the DOM). In vanilla JavaScript, we work with DOM elements by calling document.getElementById(), passing in the id of a given element. With refs in React, we no longer need to do this. The ref attribute will literally reference that element and give us access to it’s methods.

Here is an example of putting a ref in an input tag:

<input type="text" ref={textInput} />

We can also use a ref inside of a component (but only within the render method of a parent component):

<FormComponent ref={formRef} />

The ref attribute is the inspiration for the useRef but it is not the only reason to use this hook. Let’s get into the useRef a little more.

What is useRef?

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. (Hooks API Reference — React)

This is a heady definition — the basics of the useRef is that it is an object in which mutable information can be stored without triggering a re-render. The .current property is what will be initialized and where the most recent information is stored. As I’ve mentioned, this can be particularly useful for working with DOM elements but this hook is useful for a lot more than that because it can change at any time during a component’s lifecycle without triggering a re-render.

Getting Started

Import the useRef hook into your React component at the top:

import React, { useRef } from 'react';

Once you have the hook imported, you can begin using it. The useRef hook is initialized in the same way as the useState hook:

const textInput = useRef('');

The value passed into useRef will be the initial value, which is stored on .current property. In this example: textInput.current = '';

Using useRef to access elements

Running with our example of the text input, let’s look at how we could use the useRef hook to interact with a DOM element by switching the focus to the input box:

Here we give the button an onClick function that calls the focus() method on our useRef hook, textInput. When the button clicks, the user’s focus on the page switches to the that text box. Since we are putting the ref in the input element, we then have access to any methods for that particular HTML element, like the focus() method.

Using useRef to store information in State

As I’ve said a few times now, the useRef hook can store information that can be changed throughout the lifecycle of the component without triggering a re-render.

Get Kris Mason’s stories in your inbox

Join Medium for free to get updates from this writer.

This has many use cases, but by way of example, let’s imagine we wanted to keep track of the number of times a component re-rendered. We might try to do something like this:

However, since anything stored in the state is going to trigger a re-render when it changes, every time we increment count our component will render again and thus create an infinite loop. So this is an example of something not to do! But we do need to store this number somewhere in the state, so the component can keep track of it over the course of its entire lifecycle.

Enter the useRef again. By simply changing count to be a useRef hook rather than a useState hook, we can safely store this mutated data without re-rendering:

Note that useRef doesn’t come with it’s own setter like useState hooks do. To alter a ref we simply reassign any value stored on the .current property of the useRef.

Another note of caution: it is recommended to run any side effects, like altering a ref, inside a useEffect or a useLayoutEffect to avoid bugs.

Conclusion

The useRef hook is a very handy option for both interacting with DOM elements and storing mutating information in your app without triggering a re-render. However, it is suggested to only use the useRef when necessary and within a useEffect to avoid bugs.

This article is a quick introduction to the useRef hook. There is a lot going on in the world of useRef and refs in React. Here are some articles to get you started:

--

--

Written by Kris Mason

Software Engineer based in New Orleans, LA