React useRef
useRef gives a component a little box that survives re-renders: an object with a single current property. Unlike state, changing ref.current does not cause a re-render. Refs have two main jobs:
- Holding a reference to a DOM element (to focus it, measure it, scroll to it).
- Remembering a mutable value that isn't shown on screen (a timer id, a previous value, a counter).
const ref = useRef(initialValue); // { current: initialValue }Accessing DOM elements
Pass the ref to an element's ref attribute. After React creates the DOM node, it puts it into ref.current:
import { useRef } from 'react';
export default function App() {
const inputRef = useRef(null);
const bottomRef = useRef(null);
return (
<div>
<input ref={inputRef} placeholder="Click the button to focus me" style={{ width: 240 }} />{' '}
<button onClick={() => inputRef.current.focus()}>Focus input</button>{' '}
<button onClick={() => { inputRef.current.value = ''; inputRef.current.focus(); }}>Clear</button>
<div style={{ height: 300, background: 'linear-gradient(#fff, #def)', margin: '10px 0' }}>
<button onClick={() => bottomRef.current.scrollIntoView({ behavior: 'smooth' })}>Scroll to bottom ↓</button>
</div>
<p ref={bottomRef}>🎉 You reached the bottom.</p>
</div>
);
}Note:
ref.currentisnullduring the first render, because the DOM node doesn't exist yet. Read DOM refs in event handlers or effects, never while rendering.
Storing a timer id
A stopwatch must remember its interval id to stop it later. The id isn't displayed, so a ref is the right place — a state variable would cause useless re-renders, and a plain variable would be lost on the next render:
import { useRef, useState } from 'react';
export default function App() {
const [ms, setMs] = useState(0);
const [running, setRunning] = useState(false);
const intervalRef = useRef(null);
function start() {
if (intervalRef.current) return;
setRunning(true);
intervalRef.current = setInterval(() => setMs((t) => t + 100), 100);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
setRunning(false);
}
function reset() {
stop();
setMs(0);
}
return (
<div>
<p style={{ fontSize: 36, fontFamily: 'monospace', margin: 0 }}>{(ms / 1000).toFixed(1)}s</p>
<button onClick={start} disabled={running}>Start</button>{' '}
<button onClick={stop} disabled={!running}>Stop</button>{' '}
<button onClick={reset}>Reset</button>
</div>
);
}Refs vs. state
useState |
useRef |
|
|---|---|---|
| Survives re-renders | ✅ | ✅ |
| Changing it re-renders | ✅ | ❌ |
| How to change | setValue(x) |
ref.current = x |
| Read during render | ✅ | ❌ (avoid — it may be stale) |
| Typical use | anything shown on screen | DOM nodes, timer ids, previous values |
This demo makes the difference visible. Both buttons count clicks, but only the state version updates the screen:
import { useRef, useState } from 'react';
export default function App() {
const [stateCount, setStateCount] = useState(0);
const refCount = useRef(0);
return (
<div>
<button onClick={() => setStateCount(stateCount + 1)}>State clicks: {stateCount}</button>{' '}
<button
onClick={() => {
refCount.current += 1;
console.log('ref clicks:', refCount.current);
}}
>
Ref clicks: {refCount.current}
</button>
<p>The ref button's label only catches up when something else re-renders (click the state button).</p>
</div>
);
}Remembering the previous value
Combining a ref with an effect lets you remember what a value was on the previous render:
import { useEffect, useRef, useState } from 'react';
export default function App() {
const [price, setPrice] = useState(100);
const prevPrice = useRef(price);
useEffect(() => {
prevPrice.current = price; // runs after render, so render saw the old value
}, [price]);
const prev = prevPrice.current;
const trend = price > prev ? '📈 up' : price < prev ? '📉 down' : '➖ unchanged';
return (
<div>
<p style={{ fontSize: 22 }}>Price: ${price} ({trend} from ${prev})</p>
<button onClick={() => setPrice(price + 5)}>+5</button>{' '}
<button onClick={() => setPrice(price - 5)}>−5</button>
</div>
);
}Note: This pattern reads a ref during render, which the rule of thumb above advises against. It is a well-known exception that works here because the value only changes in an effect, but prefer keeping the previous value in state when you can.
Passing refs to your own components
In React 19, ref is a normal prop for function components. A custom input can forward it to the real <input>:
function FancyInput({ ref, label }) {
return <label>{label} <input ref={ref} /></label>;
}
function Form() {
const nameRef = useRef(null);
return <FancyInput ref={nameRef} label="Name" />;
}Older code wraps such components in forwardRef(...); React 19 no longer needs that.
Test yourself
What happens when you assign ref.current = 5?
- The component re-renders
- The value is stored, but no re-render happens
- React throws an error
- The ref is reset on the next render
What is inputRef.current during the very first render?
- The input DOM node
- null (or the initial value)
- undefined always
- A React element
Which value belongs in a ref rather than state?
- The text shown in a heading
- A setInterval id used only to stop the timer
- The list of todos
- Whether a modal is visible