Sub topic 1
What useRef returns
Prerequisites
This chapter assumes you know:
- JavaScript objects, closures, and functions.
- React function components and JSX.
useStateand how a state change causes a re-render.- Basic
useEffect.
The return value
useRef takes one argument, the initial value. It returns a plain object with a single property named current.
import { useRef } from 'react';
export function Counter() {
const countRef = useRef(0);
console.log(countRef); // { current: 0 }
return null;
}The object is created on the first render. On every later render, React returns the same object. It does not create a new one. The current property is mutable, so you can assign to it directly.
Why it differs from a local variable
A normal variable inside a component is recreated on each render. A ref object is not. React keeps it with the component between renders, so a value stored in current is still there next time.
Changing current does not trigger a re-render. React does not watch the property. The new value is visible the next time any code reads it, such as an event handler or an effect.
A first example
This component keeps a ref to an input. The ref starts as null. React sets inputRef.current to the DOM node after the component mounts, and the click handler uses it.
import { useRef } from 'react';
export function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search" />
<button onClick={() => inputRef.current.focus()}>Focus the input</button>
</>
);
}Passing ref={inputRef} to a built-in element tells React to store that element's DOM node in inputRef.current. The DOM node is just one use. A ref can hold any value.
Comparing the three tools
| Tool | Survives renders | Change causes re-render |
|---|---|---|
| Local variable | No | No |
| `useState` | Yes | Yes |
| `useRef` | Yes | No |
A ref fills the gap in the table: a value that must persist but does not appear on screen.
Common first mistakes
- Reading
ref.currentfor a DOM node before mount. It isnulluntil React attaches the node, so use it in event handlers or effects. - Expecting the screen to update after setting
current. Use state for values you display. - Replacing the ref object instead of its property. Write
ref.current = 5, notref = 5.
Exercise
A component calls const idRef = useRef(10) and later runs idRef.current = 20 inside a click handler. What does idRef hold on the next render, and does the click cause a re-render?
Show answer
idRef is the same object as before, and its current is 20. The assignment alone does not cause a re-render. A render caused by something else, such as a state change, will see 20.