React / 82
useRef: remember without re-rendering
A ref is a box with a .current property. It survives re-renders but never causes one. Use it for timer ids and to reach real DOM nodes.
The shape
import { useRef } from "react";
const countRef = useRef(0); // { current: 0 }
countRef.current = countRef.current + 1; // change it whenever you likeuseRef(initialValue)returns a plain object,{ current: initialValue }.- React gives you the same object on every render.
- You change it by assigning to
.current. React isn't told, so nothing re-renders.
Ref vs state
useState
for what the screen shows
you call
setCount(count + 1)
re-render
Component runs again
Screen shows the new count
useRef
for what the screen doesn't need
you write
countRef.current += 1
the box
{ current: 4 }
Used in a handler or effect
useState | useRef | |
|---|---|---|
| Gives you | [value, setValue] | { current: value } |
| Change it with | the setter | ref.current = … |
| Re-renders? | Yes | No |
| Inside one render | a fixed snapshot | can change at any time |
| Read it in | render, handlers, effects | handlers and effects |
A ref vs state
Try itclicksRef.currenton screen
0
console.log → 0
count (state)on screen
0
each click re-renders the whole component
Example: a timer you can stop
import { useRef, useState } from "react";
export default function Timer() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
function start() {
if (intervalRef.current !== null) return; // already running
intervalRef.current = setInterval(() => setSeconds((s) => s + 1), 1000);
}
function stop() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
return (
<>
<p>{seconds}s</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</>
);
}seconds is on screen, so it's state. The interval id is never shown, but stop needs it after many re-renders, so it lives in a ref. With let intervalId, every tick would re-render, the variable would start over as undefined, and Stop would clear nothing.
Refs to DOM nodes
The most common use: pass a ref object to an element's ref attribute, and React puts the real DOM node into .current.
import { useRef } from "react";
export default function SearchBar() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search dishes" />
<button onClick={() => inputRef.current.focus()}>Search</button>
</>
);
}- renderReact calls your component. On the first render
inputRef.currentis stillnull: the input doesn't exist yet. - commitReact creates the
<input>and setsinputRef.currentto that DOM node. - effectsEffects run. The node is ready: focus it, measure it, scroll to it.
- clicksEvent handlers can use it any time while the input is on the page.
- unmountThe input is removed and React sets
inputRef.currentback tonull.
React manages the DOM for you, but a few things can only be done by calling browser methods on a node:
| Job | Call |
|---|---|
| Focus an input | inputRef.current.focus() |
| Scroll to an element | itemRef.current.scrollIntoView({ behavior: "smooth", block: "nearest" }) |
| Measure size or position | boxRef.current.getBoundingClientRect() |
| Play a video | videoRef.current.play() |
Reach into the DOM
Try it- Masala dosa
- Paneer wrap
- Veg biryani
- Chole bhature
- Idli sambar
- Pav bhaji
- Mango lassi
- Gulab jamun
- Click a button to see the call.
Use refs for these "imperative" jobs only. Don't use them to change text, classes or children by hand: React owns that and will overwrite your changes on the next render.
Don't read or write refs during render
Don't
Touch the ref while rendering
function Counter() {
const clicksRef = useRef(0);
clicksRef.current++; // write during render
return <p>Rendered {clicksRef.current} times</p>; // read during render
}React may call your component more than once per update (StrictMode does it on purpose in development), so the write can run more often than you think. And React can't see ref changes, so the screen goes stale.
Do
Touch it in handlers and effects
function Counter() {
const [clicks, setClicks] = useState(0);
return (
<button onClick={() => setClicks(clicks + 1)}>
Clicked {clicks} times
</button>
);
}If it's on screen, it's state. Refs are for handlers and effects.
Rendering should be pure: the same props and state give the same JSX, with no side effects. A ref breaks both halves. The react-hooks/refs rule in recent versions of the React Hooks ESLint plugin flags it for you.
One exception is allowed: creating something expensive once.
const playerRef = useRef(null);
if (playerRef.current === null) {
playerRef.current = new VideoPlayer(); // runs on the first render only
}Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
