React useRef Hook
The useRef
hook is a powerful tool provided by React that allows you to persist values across renders without triggering a re-render of the component. It serves various purposes, from accessing DOM elements to storing mutable values that don't cause a component to update when they change. Here’s a detailed explanation of its uses and how it works:
Accessing DOM Elements
The most common use of useRef
is to access a DOM element directly. By assigning the ref object to a JSX element's ref
attribute, you can interact with that element directly, such as focusing on an input or measuring its dimensions. This is particularly useful for managing focus, animations, or integrating with third-party DOM libraries.
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type='text' />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Storing Mutable Values
useRef
can also be used to store any mutable value. Unlike state variables created with useState
, updating a ref does not cause the component to re-render. This makes refs a good place to store values that you want to keep track of between renders but don’t need to be reactive, such as timers, subscription IDs, or previous props/state values for comparison.
function TimerComponent() {
const intervalId = useRef(null);
useEffect(() => {
intervalId.current = setInterval(() => {
console.log('Timer is running');
}, 1000);
return () => clearInterval(intervalId.current);
}, []);
return <div>Check the console to see the timer log.</div>;
}
How useRef
Works
- When you create a ref by calling
useRef
, you receive an object with a propertycurrent
. This object persists for the lifetime of the component, allowing you to set itscurrent
property to anything you want to keep track of. - The value stored in
ref.current
is mutable and can be changed to anything without causing a re-render. This is unlike state variables, where updates cause the component to re-render. - The object returned by
useRef
will be the same between renders, making it ideal for keeping track of values and state across renders without causing unnecessary updates.
When to Use useRef
- Accessing and interacting with DOM elements: When you need to directly interact with an element, such as focusing on an input or measuring its size.
- Storing previous state or props for comparison: Useful in
useEffect
to compare against current props/state. - Storing values that don't cause re-renders when changed: Ideal for values that are used within event handlers, timeouts, or other asynchronous code where you don’t want UI updates in response to changes.
Conclusion
In conclusion, useRef
is a versatile hook that can be used for more than just accessing DOM elements. It provides a way to persistently store data across renders without affecting the component's re-rendering behavior, making it an essential tool in the React developer's toolbox.