What is the useRef hook in React used for?

In React, hooks have revolutionized how we build and manage stateful logic in functional components. One of the most versatile hooks is useRef(), which allows us to create and maintain mutable referencesMutable references refer to references that can be changed or updated during the execution of a program. to elements or values across renders.

What is useRef()?

The useRef() hook is a built-in hook provided by React that returns a mutable ref object. The ref object persists across renders and allows us to keep a reference to a specific element or value. It is important to note that useRef() does not cause re-rendering when its value changes, making it an ideal choice for storing mutable data without triggering unnecessary updates.

Syntax

The syntax for the useRef() hook in React is as follows:

import React, { useRef } from 'react';
function Component() {
const refName = useRef(initialValue);
// Rest of the component logic
}

The initialValue parameter is optional. If provided, it sets the initial value of the ref object. However, the most common use case is to initialize the ref object with null since the value will be assigned and accessed through the .current property.

Once we have the ref object, we can use refName.current to access or update the current value of the ref.

Basic usage

Let’s begin by exploring the basic usage of the useRef() hook. Here’s how we can use it to create a ref that will be used to reference an input element, enabling us to interact with its value or other properties.

Explanation

  • Line 5: This line initializes a ref called inputRef using the useRef() hook. The initial value of the ref is set to null.

  • Lines 7–10: This line defines a function called handleClick that will be executed when the button is clicked and logs the current value of the inputRef using inputRef.current.value. It accesses the value property of the current ref value.

  • Line 14: This line renders an <input> element of type "text". The ref attribute is set to inputRef, which allows us to reference and access the DOM node of the input element through the ref.

  • Line 15: This line renders a <button> element with the text "Get Value". The onClick event is attached to the handleClick function, which will be executed when the button is clicked.

To learn how it works, see your console.

Using useRef() to manage focus

One common use case for the useRef() hook is managing focus within components. Let’s consider a case where we have an input field that we want to autofocus when a component mounts:

In the example above, we create a ref object inputRef and assign it to the ref prop of the <input> element. Within the useEffect hook, we utilize inputRef.current.focus() to focus the input element when the component mounts. By passing an empty dependency array [], we ensure that the effect runs only once after the initial render.

Caching expensive calculations

Another powerful use case for useRef() is caching expensive calculations or values that don’t trigger re-renders. Let’s consider an example where we need to calculate the factorial of a given number:

In the example above, we create two ref objects: inputRef and resultRef. The inputRef holds a reference to the input element, allowing us to extract the user’s input value. The resultRef refers to the <p> element, which will display the calculated factorial. By using resultRef.current.textContent, we update the content of the paragraph element without causing a re-render.

Conclusion

The useRef() hook is a powerful tool that provides a way to maintain mutable references across renders, allowing us to manage focus, cache values, or store other mutable data without triggering unnecessary re-renders. By utilizing useRef(), we can enhance the performance and functionality of our React components.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved