React Hooks In DepthLesson 3.2
useRef hook: DOM access and mutable values in React
useRef syntax, DOM element access, mutable ref container, ref vs state, focus management, previous value tracking, avoiding re-renders with refs
useRef: Two Use Cases
useRef returns a mutable object whose .current property persists across renders. Unlike state, changing a ref does not trigger a re-render. It has two primary use cases.
1. Accessing DOM Elements
import { useRef } from 'react';
function SearchInput() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} type="text" placeholder="Search" />
<button onClick={focusInput}>Focus</button>
</>
);
}2. Storing Mutable Values Without Re-renders
import { useRef, useState, useEffect } from 'react';
function Timer() {
const [running, setRunning] = useState(false);
const intervalRef = useRef(null);
function start() {
setRunning(true);
intervalRef.current = setInterval(() => {
console.log('tick');
}, 1000);
}
function stop() {
setRunning(false);
clearInterval(intervalRef.current);
}
return (
<>
<button onClick={start} disabled={running}>Start</button>
<button onClick={stop} disabled={!running}>Stop</button>
</>
);
}Store timer IDs, previous prop values, or any value that must persist without causing re-renders. If a value change should update the UI, use state instead. If it's purely internal plumbing, use a ref.
