Sub topic 1
React useRef: Mutable Values and Direct DOM Access
Prerequisites
This chapter assumes JavaScript objects and functions, React function components and JSX, useState, basic useEffect, and DOM concepts such as focus and scrolling.
What useRef returns
useRef returns a stable object with one property, current:
const countRef = useRef(0);
console.log(countRef.current); // 0The argument is the initial value. React returns the same ref object on later renders. You can change ref.current directly:
countRef.current = 1;Changing it does not update the screen and does not schedule another render.
A value that survives renders without causing them
A render is React's calculation of what the UI should look like. State changes request another render. Ref changes do not.
import { useRef, useState } from 'react';
export function ClickCounter() {
const [visibleCount, setVisibleCount] = useState(0);
const clickCountRef = useRef(0);
function handleClick() {
clickCountRef.current += 1;
setVisibleCount((count) => count + 1);
}
return (
<button onClick={handleClick}>
Rendered clicks: {visibleCount}
</button>
);
}The ref records a mutable value for event handlers or effects. Since that value is not displayed, a ref is appropriate.
Ref or state: how to decide
Ask whether changing the value must update the UI.
| Use state when | Use a ref when |
|---|---|
| The value appears in rendered output | The value is an implementation detail |
| A change should trigger a render | A change must not trigger a render |
| React should track the update | You need a mutable value between renders |
A timer ID, DOM node, or latest callback usually belongs in a ref. A displayed count, selected tab, or loading message belongs in state.
Getting a handle on a DOM element
Pass a ref to a DOM element. React sets current to that element after mounting and resets it to null when it is removed.
import { useRef } from 'react';
export function SearchBox() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} placeholder="Search" />
<button onClick={focusInput}>Focus input</button>
</>
);
}The optional chaining operator prevents an error if the button runs before the input has mounted. Once available, the ref permits imperative DOM actions such as focus(), scrollIntoView(), and getBoundingClientRect().
Exercise
Which should store a visible score: state or a ref?
Show answer
State, because changing the score must cause React to render the new value.