What is the useRef hook in React used for?

Key takeaways:

  • useRef() stores mutable references to DOM elements or values without triggering re-renders, making it ideal for tasks like managing focus, caching expensive calculations, and improving performance.

  • The useNavigate() hook from react-router-dom allows programmatic navigation in React apps, enabling seamless transitions between routes by invoking a function with a URI.

  • useRef() is useful for managing focus within components, allowing elements like input fields to be auto-focused without triggering unnecessary re-renders. useRef() helps in performance optimization by caching values, such as calculation results, without causing re-renders, which can be particularly beneficial in scenarios like complex mathematical computations.

  • useNavigate() is limited to functional components within a Router instance, ensuring controlled and dynamic route management in React applications.

  • Using useRef() instead of useState() for mutable data ensures that DOM manipulation can happen without affecting the component’s lifecycle or causing performance issues.

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. Understanding the React useRef hook is crucial for scenarios where you need to interact with DOM elements directly without causing unnecessary re-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. This distinction makes it different from using useState, which triggers a re-render when updated. This makes useRef() particularly useful for performance optimization in React.

If you're new to React, consider reading our detailed blog "A Step-by-Step Guide To Learn React" to get familiar with core concepts like functional components and hooks, which will help you better understand the concepts given in this Answer.

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
}
Creating a mutable reference with initial value

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, which is a key aspect of using useRef() for DOM manipulation in React.

Basic usage of the useRef() hook

Let’s begin by exploring the basic usage of the useRef() hook. Here’s how we can use it to create a ref that references an input element, enabling us to interact with its value or other properties. This example is a typical use case when learning a useRef() hook tutorial.

In the above App.js file:

  • 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 section defines a function called handleClick that will be executed when the button is clicked. It logs the current value of the inputRef using inputRef.current.value, accessing the value property of the referenced DOM element.

  • Line 14: This line renders an <input> element of type "text". The ref attribute is set to inputRef, allowing 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 see how it works, type a number or text into the input field, click the button, and observe the results logged in the 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. This example will also showcase the difference between useRef and useState in focus management:

In the code above:

  • Line 4: A ref object, inputRef, is created using the useRef() hook. The initial value of the ref is set to null. This is a common practice when referencing DOM elements.

  • Lines 6–11: The useEffect hook is used to perform a side effect when the component mounts. Inside the useEffect, a conditional check ensures that inputRef.current is not null before attempting to focus the input element. This prevents runtime errors. The inputRef.current.focus() method is called to programmatically set focus on the input element when the component mounts.

    • Line 11: The [] dependency array passed to useEffect ensures that this effect runs only once after the component’s initial render, making the behavior predictable.

  • Line 13: The <input> element is assigned the inputRef object through the ref prop, creating a reference to the DOM node.

This method is effective for managing focus in practical applications. Unlike useState, which triggers a re-render, useRef allows us to manipulate the DOM directly without affecting the component's lifecycle, making it an efficient choice for this scenario. Additionally, managing focus is crucial for accessibility, ensuring users can interact with form fields intuitively.

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, demonstrating the benefits of using useRef for performance optimization in React:

In the code above:

  • Line 4: A ref object, inputRef, is created using the useRef() hook and initialized to null. This ref will hold a reference to the <input> element for extracting user input.

  • Line 5: Another ref object, resultRef, is created using useRef() and initialized to null. This ref will hold a reference to the <p> element for displaying the calculated factorial.

  • Lines 7–16: A function calculateFactorial is defined to calculate the factorial of a user-provided number.

    • Line 8: The user’s input value is retrieved using inputRef.current.value, and parseInt is used to convert it into an integer.

    • Lines 11–13: A loop calculates the factorial by iteratively multiplying numbers up to the input value.

    • Line 15: The result is displayed by directly updating the textContent of the <p> element referenced by resultRef.current.

  • Line 20: The <input> element is rendered with the ref prop set to inputRef, allowing it to be accessed programmatically.

  • Line 21: A <button> element is rendered with an onClick handler attached to the calculateFactorial function. When clicked, the function is executed.

  • Line 22: A <p> element is rendered with the ref prop set to resultRef, allowing its content to be updated programmatically without triggering a re-render.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

What is the primary advantage of using the useRef() hook in React for caching calculations?

A)

It triggers a re-render of the component when the value changes.

B)

It allows for direct manipulation of DOM elements without affecting component lifecycle.

C)

It automatically updates the state every time a calculation is performed.

D)

It simplifies the implementation of context in React components.

Question 1 of 20 attempted

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. With proper use, it can be a game-changer for performance optimization in React.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Why use useRef instead of useState?

Using useRef instead of useState is advantageous when you need to store a mutable value without causing a re-render of the component. useRef maintains its value across renders but does not trigger an update to the UI when the value changes. This is particularly useful for scenarios such as managing focus, storing previous values, or caching calculations where the UI does not need to react to the changes immediately, resulting in improved performance and reduced unnecessary renders.


What are the benefits of using useRef?

The benefits of using useRef include its ability to hold a mutable reference to a DOM element or any value that persists across renders without causing re-renders. This makes it ideal for scenarios such as managing focus, accessing DOM nodes directly, or storing values that should not affect the rendering logic. Additionally, useRef provides a simple way to optimize performance by caching expensive computations or holding mutable data that can be modified without triggering updates to the component’s state.


What are the disadvantages of useRef?

Despite its advantages, useRef does have some disadvantages. The primary limitation is that it does not trigger re-renders when its value changes, which means that any component relying on that value for rendering will not update automatically. This can lead to stale or outdated information if not managed carefully. Furthermore, useRef is not suitable for managing state that requires UI updates based on value changes, as it bypasses React’s state management mechanisms and may complicate the flow of data within the component.


What is the difference between useRef and useMemo?

The key difference between useRef and useMemo lies in their purpose and behavior. useRef is primarily used to create a mutable reference that persists across renders without causing re-renders, making it suitable for storing values or references to DOM elements. In contrast, useMemo is used to memoize expensive calculations or values, recomputing them only when their dependencies change. While useRef holds values and provides direct access to them, useMemo optimizes performance by preventing unnecessary recalculations based on the changing state or props, thus enhancing the efficiency of functional components.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved