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 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 fromreact-router-domallows 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 ofuseState()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 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}
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
inputRefusing theuseRef()hook. The initial value of the ref is set tonull.Lines 7–10: This section defines a function called
handleClickthat will be executed when the button is clicked. It logs the current value of theinputRefusinginputRef.current.value, accessing thevalueproperty of the referenced DOM element.Line 14: This line renders an
<input>element of type "text". Therefattribute is set toinputRef, 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". TheonClickevent is attached to thehandleClickfunction, 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 theuseRef()hook. The initial value of the ref is set tonull. This is a common practice when referencing DOM elements.Lines 6–11: The
useEffecthook is used to perform a side effect when the component mounts. Inside theuseEffect, a conditional check ensures thatinputRef.currentis notnullbefore attempting to focus the input element. This prevents runtime errors. TheinputRef.current.focus()method is called to programmatically set focus on the input element when the component mounts.Line 11: The
[]dependency array passed touseEffectensures that this effect runs only once after the component’s initial render, making the behavior predictable.
Line 13: The
<input>element is assigned theinputRefobject through therefprop, 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 theuseRef()hook and initialized tonull. This ref will hold a reference to the<input>element for extracting user input.Line 5: Another ref object,
resultRef, is created usinguseRef()and initialized tonull. This ref will hold a reference to the<p>element for displaying the calculated factorial.Lines 7–16: A function
calculateFactorialis defined to calculate the factorial of a user-provided number.Line 8: The user’s input value is retrieved using
inputRef.current.value, andparseIntis 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
textContentof the<p>element referenced byresultRef.current.
Line 20: The
<input>element is rendered with therefprop set toinputRef, allowing it to be accessed programmatically.Line 21: A
<button>element is rendered with anonClickhandler attached to thecalculateFactorialfunction. When clicked, the function is executed.Line 22: A
<p>element is rendered with therefprop set toresultRef, allowing its content to be updated programmatically without triggering a re-render.
Knowledge test
Let’s attempt a short quiz to assess your understanding.
What is the primary advantage of using the useRef() hook in React for caching calculations?
It triggers a re-render of the component when the value changes.
It allows for direct manipulation of DOM elements without affecting component lifecycle.
It automatically updates the state every time a calculation is performed.
It simplifies the implementation of context in React components.
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?
What are the benefits of using useRef?
What are the disadvantages of useRef?
What is the difference between useRef and useMemo?
Free Resources