DEV Community

Cover image for What is the useRef Hook in React and When Should It Be Used?
 Tijani Olagunju
Tijani Olagunju

Posted on

What is the useRef Hook in React and When Should It Be Used?

SCOPE

A React Hook is a special function in React that lets developers use state and other React features without writing a class. It makes code simpler and easier to manage by allowing functionality to be added directly within components.Now we will discuss the useRef Hook in the following sections:


📘 What is the useRef Hook in React and When Should It Be Used?

Table of Contents

1.Introduction to useRef
2.Syntax of useRef
Common Use Cases
3.1. Accessing DOM Elements
3.2. Storing Mutable Values
3.3. Persisting Values Without Re-render
Example Use Cases
4.1. Focus an Input Field
4.2. Keep Track of Previous State
4.3. Interval with Mutable Reference
5.Best Practices
6.Conclusion
Enter fullscreen mode Exit fullscreen mode



  1. Introduction to useRef

useRef is a built-in React hook that returns a mutable ref object. It is primarily used to reference DOM elements or persist values across renders without triggering a re-render.

const myRef = useRef(initialValue);
The returned object:
{ current: initialValue }
This object is mutable and persists for the lifetime of the component.


2.Syntax of useRef

Here's how you import and use it:
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
return <input ref={inputRef} />;

}
You access or modify the ref with:
inputRef.current


3.Common Use Cases

3.1.Accessing DOM Elements

You can use useRef to directly access or manipulate a DOM element, such as focusing an input field or reading values without event handlers.

3.2.Storing Mutable Values

It can hold any mutable value (like a counter or timeout ID) that shouldn't cause a re-render when updated.

3.3.Persisting Values Without Re-render

Unlike useState, changing the .current property of a ref does not trigger a re-render, making it ideal for tracking non-UI-changing values.


Example Use Cases

4.1.Focus an Input Field

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

4.2.Keep Track of Previous State

import React, { useEffect, useRef, useState } from 'react';
function PreviousValueExample() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
});
return (
<div>
<p>Current: {count}</p>
<p>Previous: {prevCountRef.current}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

4.3.Interval with Mutable Reference

import React, { useRef, useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(intervalRef.current);
}, []);
return (
<div>
<p>Timer: {seconds}s</p>
<button onClick={() => clearInterval(intervalRef.current)}>Stop</button>
</div>
);
}


5.Best Practices

  • ✅ Use useRef for non-rendering values or DOM access.
  • ❌ Avoid using useRef to replace all useState — they serve different purposes.
  • ✅ Use useRef to store mutable variables like timers, counters, or previous props/state.
  • ❌ Don’t use useRef to track values that should appear in the UI without forcing updates manually.

6.Summary

The useRef hook is a powerful tool in React for handling references to DOM elements and persisting mutable data across renders without causing re-renders. It's an essential hook for performance optimization, direct DOM access, and managing non-reactive values.
Use it wisely alongside useState and useEffect to build efficient, interactive React components.
questions are welcomed in the comment box.

Top comments (0)