Effects and essential hooks · Lesson 13 of 21
useRef
Reaching the DOM, and a remembered value that doesn't re-render.
useRef returns an object { current: … } that stays the same for the component's whole life. Two uses:
1. Reach a DOM element (focus it, measure it, scroll to it). 2. Remember a value between renders without re-rendering when it changes (like a timer id).
function App() {
const inputRef = useRef(null)
const clicks = useRef(0)
const [shown, setShown] = useState(0)
return (
<div>
<input ref={inputRef} placeholder="Search courses" />
<button onClick={() => inputRef.current.focus()}>Focus the search</button>
<hr />
<button onClick={() => { clicks.current++ }}>Count silently</button>
<button onClick={() => setShown(clicks.current)}>Show count</button>
<p>Silent clicks shown: {shown}</p>
</div>
)
}| useState | useRef | |
|---|---|---|
Change re-renders? | yes | no |
Read during render? | yes | better not |
How you change it | setX(v) | ref.current = v |
Uses | anything shown on screen | DOM, timer ids, previous values |
function Stopwatch() {
const [ms, setMs] = useState(0)
const timer = useRef(null)
const start = () => {
if (timer.current) return
timer.current = setInterval(() => setMs((t) => t + 100), 100)
}
const stop = () => {
clearInterval(timer.current)
timer.current = null
}
useEffect(() => stop, []) // stop when the component goes away
return (
<div>
<h2>{(ms / 1000).toFixed(1)}s</h2>
<button onClick={start}>Start</button> <button onClick={stop}>Stop</button>
</div>
)
}
function App() {
return <Stopwatch />
}Complete the code
Complete it so the input is focused as soon as the page opens.
function App() { const box = (null) useEffect(() => { box..focus() }, []) return <input ref={box} /> }
Exercise
A Tap button counts presses in a ref without re-rendering, and a Show button copies the count into state and displays it: Taps: N. The checker presses Tap three times, then Show.
Taps: 3 Tap Show
function App() {
const taps = useRef(0)
return (
<div>
<p>Taps: 0</p>
<button className="tap">Tap</button>
<button className="show">Show</button>
</div>
)
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.