A component sometimes needs to remember data that it doesn't need to show, such as a timer's id, a render count, or the input element you want to focus. If you keep that data in state, every change causes a re-render nobody needs. If you keep it in a plain variable, it's lost on every render. For data like this, React has useRef.
useRef gives a component a box that React remembers between renders. This box is called a ref. You can change what's inside it at any time without triggering a re-render. A ref has two jobs: keeping a value that doesn't need to be shown, and holding a real DOM element (for example, to move the cursor into an input). Remember the futsal scoreboard from the useState lesson? The score on the board is state: the moment it changes, every spectator sees the new number. A ref is like the referee's pocket notebook. The referee can write in it whenever he likes, and no spectator sees the note change. But the note is still there when he opens the notebook again. In React, the note in the notebook is what's inside the ref: changing it doesn't change the screen, but it's still there on the next render.
A box remembered between renders
This code makes a ref named clicksRef that starts at 0, then changes what's inside:
const clicksRef = useRef(0)
console.log(clicksRef) // { current: 0 }
clicksRef.current = 5 // change what's inside
console.log(clicksRef.current) // 5
useRef(0)returns an object with one property,current, which starts out holding0.- On every render, React returns the same object. So what's in
currentisn't lost when the component re-renders. That's unlike a plainletvariable, which is made from scratch on every render. - You read and change what's inside through
.current:clicksRef.current = 5,clicksRef.current++. - Changing
.currenttells React nothing, so there's no re-render. That's the difference from auseStatesetter, which asks for a re-render. - In a real project, hooks are imported first:
import { useRef } from 'react'. In the exercise editor,useRef,useStateanduseEffectare already available. You may write the import line, but you don't have to.
A ref changes without a re-render
This component keeps two click counts: one in a ref (clicksRef) and one in state (clicks). Its paragraph shows both, and each count has its own button:
function App() {
const clicksRef = useRef(0)
const [clicks, setClicks] = useState(0)
function addRef() {
clicksRef.current++ // change the ref: no re-render
console.log(clicksRef.current)
}
return (
<div>
<p>ref: {clicksRef.current} · state: {clicks}</p>
<button onClick={addRef}>clicksRef.current++</button>
<button onClick={() => setClicks((c) => c + 1)}>setClicks</button>
</div>
)
}
Take a guess before you look at the table: the clicksRef.current++ button is clicked three times. Does the ref number on screen become 3, or stay 0?
| Event | clicksRef.current |
Console | On screen |
|---|---|---|---|
| First render | 0 | ref: 0 · state: 0 | |
Click clicksRef.current++ |
1 | 1 | ref: 0 · state: 0 |
| Click again | 2 | 2 | ref: 0 · state: 0 |
| Click again | 3 | 3 | ref: 0 · state: 0 |
Click setClicks |
3 | ref: 3 · state: 1 |
The console prints 1, 2, 3, because .current changes right away and always holds the latest value. But the screen stays at 0, because there's no re-render. Once the setClicks button is clicked, the state changes and the component re-renders. Only then is the 3 inside the ref read and shown.
Counting renders
This component keeps its number of renders in the ref renderCount. Each click on the Update button changes the state value, so the component re-renders:
function App() {
const [value, setValue] = useState(0)
const renderCount = useRef(0)
useEffect(() => {
renderCount.current = renderCount.current + 1 // goes up after every render
}) // no dependency array: runs after every render
return (
<div>
<span id="render-count">{renderCount.current}</span>
<button id="update" onClick={() => setValue((v) => v + 1)}>Update</button>
</div>
)
}
| Event | Shown in #render-count |
renderCount.current after the effect |
|---|---|---|
| First render | 0 | 1 |
| Click Update, render 2 | 1 | 2 |
| Click Update, render 3 | 2 | 3 |
An effect runs after the render. So the number shown is how many renders came before this one: 0 at first, and 1 after one click. This table is for code without StrictMode: in development, StrictMode runs effects on mount twice, so after the first click it shows 2. Changing a ref in an effect doesn't trigger another render. If you kept the count in state instead, calling setRenderCount in an effect with no dependency array would trigger a render, then the effect would run again, forever. In general, the React documentation advises against reading .current during render, for example in JSX. This example reads .current in JSX on purpose, so you can see that a ref doesn't trigger a render.
Holding a DOM element: focusing an input
A ref can also hold an element on the page. This component moves the cursor into the input field when the Focus button is clicked:
function App() {
const inputRef = useRef(null)
return (
<div>
<input id="name" ref={inputRef} />
<button id="focus" onClick={() => inputRef.current.focus()}>Focus</button>
</div>
)
}
useRef(null): when the ref is made, the element doesn't exist yet, so it starts asnull.ref={inputRef}is a special React attribute. After the render, React fillsinputRef.currentwith the real<input>DOM element. That element is the same objectdocument.getElementById('name')would give you.inputRef.current.focus()calls the input element's built-in method, which moves the typing cursor into that field. No state changes, so there's no re-render.- Use
inputRef.currentin an event handler or an effect, not in the component body. While the first render is running, the element doesn't exist yet andinputRef.currentis stillnull. - In React 19, you can also pass a ref to your own component as a normal prop:
function Input({ ref, ...props }) { return <input ref={ref} {...props} /> }. ThisInputcomponent passes the ref on to the<input>inside it. Code for React before version 19 usesforwardReffor the same thing.
State or ref?
Use useState |
Use useRef |
|---|---|
| The value is shown on screen | The value is only used behind the scenes |
| Changing it triggers a re-render | Changing it doesn't trigger a render |
| Examples: items in a cart, text being typed | Examples: a setInterval id, a DOM element, a render count |
⚠️ A screen that doesn't move, and a .current that's still null
- Showing data from a ref and expecting the screen to follow. The screen only updates on a re-render. If the value must be shown, keep it in state.
inputRef.focus()without.current.inputRefis only the box. The element is ininputRef.current.- Raising the render count in the component body.
renderCount.current++outside an effect runs before the number is shown, so it starts at 1, not 0. Raise it in auseEffectwith no dependency array. - Forgetting
ref={inputRef}on the element. Without that attribute,inputRef.currentstaysnull, and calling.focus()throws an error.
TL;DR: The useRef(initial) hook makes a box { current: initial } (called a ref) that's the same on every render. Read and change it through .current. Changing .current doesn't trigger a re-render. For example, a ref clicksRef is raised three times with clicksRef.current++ and printed each time with console.log(clicksRef.current). The console prints 1, 2, 3, but the screen keeps the old value until something re-renders. For a DOM element, make a ref with useRef(null) (named inputRef, for example), add ref={inputRef} to the element, then call inputRef.current.focus() in an event handler to move the cursor into that element. A render count goes up in a useEffect with no dependency array, which runs after the render, so it shows 0 at first and 1 after one re-render. A value that must be shown goes in state, the rest can live in a ref.
⚡ A box remembered between renders
Write:
const clicksRef = useRef(0)
console.log(clicksRef) // { current: 0 }
clicksRef.current = 5 // change what's inside
console.log(clicksRef.current) // 5
Meaning: useRef(initial) makes a box { current: initial }, called a ref. React gives you the same box on every render, so what's inside isn't lost. You read and change what's inside through .current.
⚡ The ref changes, the screen doesn't
Guess first: a component shows {clicksRef.current} on screen, and a button runs clicksRef.current++. The button is clicked three times. Does the number on screen become 3, or stay 0?
It stays 0. What's in .current does go up to 3 right away, but changing .current doesn't trigger a re-render, so the screen isn't updated.
Meaning: A value shown on screen uses useState, because its setter triggers a re-render. A value used behind the scenes, such as a setInterval id or a DOM element, uses useRef.
⚡ Holding a DOM element
Write:
function App() {
const inputRef = useRef(null)
return (
<div>
<input id="name" ref={inputRef} />
<button id="focus" onClick={() => inputRef.current.focus()}>Focus</button>
</div>
)
}
Meaning: Because of the ref={inputRef} attribute, React fills inputRef.current with the real <input> element after the render. inputRef.current.focus() moves the typing cursor there. Call it in an event handler or an effect, because during the first render .current is still null.