Sub topic 2
Focusing, scrolling, and measuring with React refs
Assume you know JavaScript objects and closures, React function components and JSX, useState, basic useEffect, and DOM terms such as focus and scrolling.
Focusing, scrolling, and measuring
A ref is useful when an event handler needs direct access to a DOM element. Attach the ref with the ref prop. React sets ref.current to the element after mounting and resets it to null when the element is removed.
import { useRef } from 'react';
export function ReadingPanel({ sections }) {
const searchRef = useRef(null);
const sectionRefs = useRef(new Map());
function focusSearch() {
searchRef.current?.focus();
}
function scrollToSection(id) {
sectionRefs.current.get(id)?.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
}
function measureSearch() {
const box = searchRef.current?.getBoundingClientRect();
if (box) console.log(`Width: ${box.width}px`);
}
return (
<>
<input ref={searchRef} placeholder="Search" />
<button onClick={focusSearch}>Focus search</button>
<button onClick={measureSearch}>Measure search</button>
<nav>
{sections.map((section) => (
<button key={section.id} onClick={() => scrollToSection(section.id)}>
{section.title}
</button>
))}
</nav>
{sections.map((section) => (
<h2
key={section.id}
ref={(node) => {
if (node) sectionRefs.current.set(section.id, node);
else sectionRefs.current.delete(section.id);
}}
>
{section.title}
</h2>
))}
</>
);
}Keeping timer IDs and other non-visual values
Use a ref for a value that must survive renders but does not appear on screen. Timer IDs, WebSocket objects, and third-party library instances are common examples.
Use state for seconds because the displayed value must update. Use a ref for the interval ID because changing it should not render the component again.
| Data | Use | Reason |
|---|---|---|
| Displayed seconds | State | Changes need a re-render |
| Interval ID | Ref | It is an internal handle |
Don't touch `ref.current` while rendering
Rendering should calculate the UI from props and state. Do not read or write ref.current during rendering when the result affects the output. The DOM node may not exist yet, and changing a ref does not trigger another render.
Read or write refs in event handlers and effects instead. The exception is predictable lazy initialization, such as creating a ref-held Map only when it is first needed.
Using refs inside effects and cleanup
Effects can create resources after mounting and return cleanup logic. Store the resource handle in a ref so event handlers or cleanup code can access it.
import { useEffect, useRef, useState } from 'react';
export function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
setSeconds((value) => value + 1);
}, 1000);
return () => {
clearInterval(intervalRef.current);
intervalRef.current = null;
};
}, []);
return <p>{seconds}s</p>;
}Exercise
Why is the interval ID stored in a ref instead of state?
Show answer
The ID controls cleanup but is not displayed. A ref preserves it without causing unnecessary renders.