React Hooks Series

useRef

Persist a mutable value across renders without triggering a re-render. Most commonly used to access DOM elements directly, but also handy for storing any value you need to keep around without it affecting the UI.

01 — What it is

01
The signature
const ref = useRef(initialValue);

// ref.current → the mutable value
// Changing ref.current does NOT trigger a re-render
Unlike state, mutating ref.current is intentional and doesn't cause a re-render. It's just a plain JavaScript object with a current property.
02
Two main use cases
// 1. Access a DOM element
const inputRef = useRef<HTMLInputElement>(null);
<input ref={inputRef} />
inputRef.current.focus(); // direct DOM access

// 2. Store a value that persists but doesn't affect UI
const countRef = useRef(0);
countRef.current += 1; // no re-render

02 — useRef vs useState

03
Key differences
useStateuseRef
Triggers re-render✓ yes✗ no
Value persists across renders✓ yes✓ yes
Mutable directly✗ use setter✓ ref.current
Use for UI values✓ yes✗ no
Use for DOM access✗ no✓ yes

03 — Live demo

RefTutorial — interactive

Type a name and click the button. The heading updates by reading directly from the DOM via inputRef.current — no state involved, no re-render triggered by the ref itself.

Yaseen

No re-render — useRef reads the DOM directly

Next: useContext — consume shared state anywhere in the tree without prop drilling.