The useRef Hook
The useRef hook is a built-in React hook that allows you to persist values between renders without triggering a re-render. It is most commonly used to access the DOM directly.
1. Accessing the DOM
Sometimes you need to interact with a DOM element directly, for example, to focus an input, scroll to a position, or measure an element's dimensions.
JavaScript
import { useRef } from 'react';
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>
</>
);
} 2. Persisting Values (Mutable Ref)
Unlike useState, changing a ref's `.current` property does not cause the component to re-render. This makes it perfect for storing values like timer IDs or previous state values.
JavaScript
function Timer() {
const intervalRef = useRef();
const startTimer = () => {
intervalRef.current = setInterval(() => {
console.log('Tick');
}, 1000);
};
const stopTimer = () => {
clearInterval(intervalRef.current);
};
return (
<div>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
} 3. useRef vs useState
| Feature | useState | useRef |
|---|---|---|
| Triggers Re-render? | Yes | No |
| Value Persistence? | Yes | Yes |
| DOM Access? | No (Declarative) | Yes (Imperative) |
Note: Do not use useRef for things that can be done declaratively. If you can use state to achieve the same result, prefer useState.