tsxANYreacthooksfocususeRef
tsx
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);Simple and common autofocus pattern.
Practical React Hooks recipes for UI interactions, timers, measurement, polling, and optimistic updates.
High-value day-to-day React hook recipes.
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);Simple and common autofocus pattern.
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(id);
}, []);Uses the updater form to avoid stale state issues.
const [draftName, setDraftName] = useState(name);
useEffect(() => {
setDraftName(name);
}, [name]);Use sparingly; derived state is often avoidable.
useEffect(() => {
if (!ref.current) return;
const observer = new ResizeObserver(([entry]) => {
setSize(entry.contentRect);
});
observer.observe(ref.current);
return () => observer.disconnect();
}, []);A practical measurement pattern for responsive components.
Common data loading and request coordination patterns.
useEffect(() => {
let stopped = false;
async function load() {
const data = await fetch('/api/status').then(r => r.json());
if (!stopped) setStatus(data);
}
load();
const id = setInterval(load, 5000);
return () => {
stopped = true;
clearInterval(id);
};
}, []);Polling needs cleanup and race awareness.
const [isPending, startTransition] = useTransition();
function handleAdd(todo: Todo) {
setTodos(prev => [...prev, todo]);
startTransition(async () => {
await saveTodo(todo);
refreshTodos();
});
}Transitions can keep follow-up updates non-blocking while the immediate optimistic UI stays responsive.