Understanding the useRef Hook in React
In this article, we will learn how to use the useRef
hook in React.
What is the useRef Hook?
The useRef
hook is used to create a mutable reference that persists across re-renders of the component. It is similar to the ref
attribute in class components.
In case of Vanilla JS, we can use document.querySelector('#myElement')
to get the reference of an element. But in React, we can use the useRef
hook to achieve the same functionality with a better performance.
When to Use the useRef Hook?
- Access to a DOM element. The
useRef
hook is useful when you need to store a reference to a DOM element - Storing previous values: You can use
useRef
to store previous values and compare them in the next render. - Storing mutable values: You can use
useRef
to store mutable values that don’t trigger re-renders.
Example with reference to a DOM element
Let’s see an example of how to use the useRef
hook to store a reference to a DOM element.
import React, { useRef } from "react";
function App() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
export default App;
In this example, we create a reference to the input element using the useRef
hook. When the button is clicked, the handleClick
function is called, which focuses the input element using the inputRef.current.focus()
method.
Example with avoiding re-renders
Let’s see an example of how to use the useRef
hook to store a mutable value that doesn’t trigger re-renders.
import React, { useState, useRef } from "react";
function Counter() {
const [count, setCount] = useState(0);
const countRef = useRef(0);
const increment = () => {
setCount(count + 1);
countRef.current = countRef.current + 1;
};
return (
<div>
<p>Count: {count}</p>
<p>Count (ref): {countRef.current}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
In this example, we use the useRef
hook to store the count value without triggering re-renders.
The countRef.current
value is updated directly without causing the component to re-render.
Summary
- Does not trigger re-renders: Updating a useRef value doesn’t cause the component to re-render.
- Accessing DOM nodes: Primarily used for interacting with DOM elements.
- Storing mutable values: Used to store values that persist across re-renders of the component.
- Avoid using it for state management: Use
useState
oruseReducer
for managing component state. - Always prefer useRef in React applications unless you have a specific need for querySelector. It’s safer, more efficient, and follows React’s principles of declarative programming.