How to Use the useRef Hook in React.js

How to Use the useRef Hook in React.js

Hello codedamn developers! Today, we are going to delve into a compelling feature of React.js, the useRef Hook. If you're a beginner or intermediate developer looking to strengthen your React.js skills, this is an excellent place to start. The useRef hook is not just a concept, but a powerful tool that you can use to create more efficient, effective, and understandable React applications. This blog post will provide you with an in-depth and comprehensive understanding of useRef in React.js.

Understanding useRef Hook

React 16.8 introduced us to the concept of Hooks, a new way to manage state and side effects in our React components. Hooks are functions that let you “hook into” React state and lifecycle features from functional components. These hooks were designed to simplify the code, making it easier to read, understand, and maintain.

One of these hooks is the useRef Hook. 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. The useRef hook is a function that returns an object with a current property. This object can be used to store a mutable variable that exists for the life of the component.

The interesting thing about useRef is that, unlike other Hooks such as useState or useReducer, it does not cause a component to re-render when it is called. This characteristic makes useRef particularly useful when you need to reliably access the most current state from within an event callback or an asynchronous function, without triggering an extra render.

Practical Uses of useRef Hook

The useRef Hook can prove to be incredibly beneficial in multiple scenarios. Here are a few common use cases:

  • Managing Focus, Text Selection, and Media Playback: You can use useRef to manage keyboard focus, text selection, or even media playback from your components. By assigning a ref to an input element, you can manipulate these properties directly from your component functions, without needing to attach event handlers or use state variables.
  • Triggering Imperative Animations: useRef can be used to store the animation used in your component and access it from anywhere in your component. This is especially useful when you need to play, pause, or cancel the animation based on user interaction or other factors.
  • Integration with Third-party DOM Libraries: If you're integrating with third-party DOM libraries that require direct manipulation of DOM elements, useRef can come in handy.

Using useRef to Access DOM Elements

One of the most common uses of useRef is to access DOM elements in a functional component. Normally, in a class component, you would use the ref attribute and createRef to create a reference to a DOM element. But in a functional component, useRef can be used to achieve the same result.

Here's a simple example:

import React, { useRef } from 'react'; function TextInput() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={handleClick}>Focus the input</button> </> ); } export default TextInput;

In the example above, we use useRef to create a ref object, inputRef, and attach it to the input element in the render method. When the "Focus the input" button is clicked, the input element gets focus. This is because we're directly manipulating the DOM element represented by the inputRef object, which is the text input field.

Using useRef for Storing Mutable Variables

Another useful application of useRef is to store mutable variables that do not cause a re-render when they change. This can be helpful when you want to keep track of the previous props or state in your component. For instance, imagine a scenario where we have a component that receives a prop and we want to compare the new prop value with the old one.

Let's see an example:

import React, { useEffect, useRef } from 'react'; function PreviousValueComponent({ value }) { const previousValueRef = useRef(); useEffect(() => { previousValueRef.current = value; }); return ( <h1> Current: {value}, Previous: {previousValueRef.current} </h1> ); } export default PreviousValueComponent;

In the code above, we use useRef to store the previous value of the prop. The current value of the ref is updated in the useEffect Hook after every render. This is a simple pattern to keep track of the previous props or state inside a functional component.


Q: What is a ref in React?
A: A ref is a way to access and interact with a DOM element or a class instance in a React component. With refs, you can manage keyboard focus, text selection, or media playback.

Q: What is the difference between useRef and createRef?
A: createRef will return a new ref on every render while useRef will return the same ref each time. So useRef can be more efficient in some cases.

Q: Can useRef cause a component re-render?
A: No, useRef does not cause a component to re-render. It’s a way to access the properties of a DOM element directly, without causing extra renders.

Q: When should I use useRef?
A: useRef can be used when you need to create a mutable instance of a variable that persists for the lifetime of the component and does not cause re-renders when updated.

Q: What does the .current property represent?
A: The .current property represents the current value of the ref and is initialized to the passed argument (initialValue).

We hope this guide has helped clarify the useRef hook in React.js for you! To learn more, check out the official React.js documentation. We'll continue to share more topics like this, so stay tuned with codedamn!

As you practice and gain experience with useRef, you might discover even more use cases that we didn't cover here. Remember, the best way to learn is by doing. So don't be afraid to experiment, make mistakes, and ask questions. That's how we all grow as developers.

Happy coding, and see you in the next walkthrough!

Sharing is caring

Did you like what Vishnupriya wrote? Thank them for their work by sharing it on social media.


No comments so far