Hooks 02 · Effects and refs
Refs (useRef)
Access to the DOM, values without re-rendering, ref as a prop and useImperativeHandle.
Loading lesson…
Hooks 02 · Effects and refs
Access to the DOM, values without re-rendering, ref as a prop and useImperativeHandle.
Loading lesson…
So far a component has two kinds of values: props (they come from outside) and state (a notebook whose change causes a new render). Let's use them to write a simple stopwatch with two buttons. "Start" starts a timer, "Stop" stops it. A timer is stopped with the function clearInterval(id), which needs the number setInterval returned (lesson JavaScript 07). We have to keep that number somewhere:
function Stopwatch() {const [seconds, setSeconds] = useState(0)let id = 0 // ❌ I keep the timer's number herefunction start() {id = setInterval(() => setSeconds((s) => s + 1), 1000) // +1 every second}function stop() {clearInterval(id) // stop the timer with the number id}return (<><p>{seconds} s</p><button onClick={start}>Start</button><button onClick={stop}>Stop</button></>)}
You click Start, the seconds run. You click Stop – and they keep running. What happened:
start starts the timer and stores its number in id, say 7.setSeconds. The state changed, so React calls Stopwatch() again – and with it the line let id = 0. A new variable holding zero was created; the one holding seven belonged to the previous render.clearInterval(0). There's no timer number 0, so nothing stops.So an ordinary variable isn't enough – it doesn't survive the next render (just like the like counter from lesson React basics 03). What about state? setId(7) would keep the number, but it would cause a pointless new render – and the timer's number isn't on the screen anyway. We need memory that survives a render but causes no render itself.
And a second thing we can't do yet: reach the real element on the page. After clicking "Search", the cursor should jump back into the field. JSX describes how the page should look, but "the cursor into the field" isn't a look – it's an action with a particular element. useRef handles both.
From React basics 03 you know state is a notebook React keeps for the cook. The setter writes a new value into the notebook and at the same time rings the bell for the cook: "cook it again". In React's terms: a state change makes React call the component again and redraw it (a new render).
A ref is a drawer next to the stove. The cook can put a slip of paper into it any time ("timer no. 7") and take it out again. The drawer lasts between cookings just like the notebook, but when you put something in, nobody rings the bell – React doesn't know about the change and doesn't render the component again.
And a ref to an element on the page is a key to a particular door: React hands it to you after rendering and you can open the door – put the cursor into a field, measure an element, scroll.
The table shows typical values; on the right is where they belong:
| Value | Is it visible on the screen? | Where it belongs |
|---|---|---|
| the seconds on a stopwatch | yes | state |
| the number of a running timer | no – only the Stop button needs it | ✅ a ref |
| whether the user is at the end of the message list | no – it only decides whether to scroll | ✅ a ref |
| a text field the cursor should jump into | – it’s an element on the page | ✅ a ref to an element |
| a list of tasks | yes | state |
| the number of finished tasks | yes, but it can be calculated | nothing – calculate it |
A simple rule: what's visible belongs in state; what's just for your code belongs in a ref. And you reach an element on the page only through a ref.
Every ref is written to the same pattern. We'll show it twice: first in general and then filled in on a stopwatch that can be stopped.
import { useRef } from 'react'function MyComponent() {// useRef(initial value) returns an object { current: initial value }.// You get the same object on every render – that's the drawer.const myRef = useRef(initialValue)function handleSomething() {myRef.current = newValue // WRITE: put a slip into the drawer (nothing re-renders)doSomething(myRef.current) // READ: take out what's in the drawer// doSomething = a made-up function "do something with it"}return <button onClick={handleSomething}>…</button>}
Three questions come with every ref:
import { useRef, useState } from 'react'function Stopwatch() {const [seconds, setSeconds] = useState(0) // visible → stateconst intervalRef = useRef(0) // the timer's number: only for the code → a ref (starts at zero)function start() {// window.setInterval always returns a number; we put it into the drawerintervalRef.current = window.setInterval(() => setSeconds((s) => s + 1), 1000)}function stop() {clearInterval(intervalRef.current) // take the number out of the drawer and stop the timer}return (<><p>{seconds} s</p><button onClick={start}>Start</button><button onClick={stop}>Stop</button></>)}
What happens now:
useRef(0) creates the object { current: 0 } and keeps it.intervalRef.current. Nothing re-renders – and it doesn't have to, the number isn't visible.seconds, the component re-renders. On every render useRef returns the same object – and the 7 is still in it.clearInterval(7) stops the right timer.The difference between state and a ref in one place. The table reads by rows; the middle column is state, the right one a ref:
| State (notebook) | Ref (drawer) | |
|---|---|---|
| survives the next render | ✅ | ✅ |
| a change causes a new render | ✅ | ❌ |
| how it changes | setX(newValue) | ref.current = newValue |
| the new value is available | only in the next render (a snapshot) | at once |
| what belongs here | what’s visible on the screen | what only the code needs |
What you see: Two counters: one in state, the other in a ref. At the bottom is how many times the component rendered.
Try it:
The takeaway: A ref remembers just like state, but changing it re-renders nothing. It shows on the screen only when a render happens for another reason – which is why nothing that should be visible belongs in a ref.
Loading the interactive part…
What for: things that can't be described as "how the page should look", only as "do this with this element now": put the cursor into a field, select text, measure a size, scroll, start a video. How: you pass the ref to an element with the ref attribute and React stores the real element of the page in ref.current.
// Where each part goes: 1. at the top of the component (next to useState), 2. into the JSX the component returns, 3. into an event handler or an effect// Blanks to fill in: HTMLElementType (the element's type, say HTMLInputElement), tag (the tag, say input)// and someMethod (a method of the element, say focus).// 1. Create the ref. The <…> holds the element's type, null = no element yet.const elementRef = useRef<HTMLElementType>(null)// 2. Attach it to an element in JSX – React stores this element in elementRef.current.<tag ref={elementRef} />// 3. In an event handler or an effect, do something with the element.elementRef.current?.someMethod()
function Search() {// 1. a ref to an <input> – the type HTMLInputElement, null at the startconst inputRef = useRef<HTMLInputElement>(null)function handleSearch() {// …run the search…inputRef.current?.focus() // 3. put the cursor back into the field (focus = a browser method)}return (<><input ref={inputRef} /> {/* 2. attaching */}<button onClick={handleSearch}>Search</button></>)}
When the element gets into the ref:
Search(). The <input> element doesn't exist yet, inputRef.current is null.<input>, sees ref={inputRef} on it and puts the element into inputRef.current.focus() method – the one every field in the browser has.null back into the ref.That's why there's a question mark after current: inputRef.current?.focus(). The ?. (lesson JavaScript 06) is called optional chaining: "if the left side is null, do nothing, otherwise call focus()".
What's done with an element most often. The task on the left, the call in the middle, where it helps on the right:
| Task | Code | Where it helps |
|---|---|---|
| the cursor into a field | ref.current?.focus() | a search, an opened window, an error in a form |
| select the text | ref.current?.select() | a field with a link to copy |
| scroll to an element | ref.current?.scrollIntoView({ behavior: 'smooth' }) | jumping to an item of a list |
| measure the size | ref.current?.getBoundingClientRect() | a tooltip next to an element, charts |
| start a video | ref.current?.play() | your own player |
What you see: Three typical tasks that can't be done by description: putting the cursor into a field, measuring an element and scrolling to an item of a list. Each uses a ref to a different element.
Try it:
The takeaway: A ref is a key to an element of the page. You use it for actions, not for the look – JSX still describes the look.
Loading the interactive part…
The "→ Tom" button in the demo scrolls to Tom. For that it needs the key to the <li> element with Tom – and the same for each of the eight cats, because a button can point at any of them. So far you know one ref for one element. How do you get eight keys?
Not like this: calling useRef for every cat right inside map.
{cats.map((cat) => {const catRef = useRef(null) // ❌ a hook inside a loopreturn <li key={cat} ref={catRef}>🐱 {cat}</li>})}
It doesn't work, for two reasons:
useRef call goes away too and React mixes up the values.catRef variable exists only inside the function in map. The scrollTo function, which should scroll to Tom, can't reach it.The idea: so far you've given React a drawer (a ref object) and it put the key in by itself. With eight doors you do it differently: you give React a phone number – "once you've built the door, call me and hand me the key". You then hang the keys on a key rack with labels yourself, the cat's name above each hook. Three steps, one at a time.
Step 1: the ref attribute takes a function too.
<input ref={(node) => console.log(node)} />// after rendering the console shows: <input>
The ref attribute accepts two different things. Given a ref object (ref={inputRef}), React stores the element in it by itself: inputRef.current = element. Given a function, React calls it and passes the element as the argument: fn(element). The parameter is usually called node (the word for an element of the page). A function you give to someone so they call it later is a callback – just like onToggle from JavaScript 10, which the parent gives to the child and the child calls on a click. Hence callback ref. React calls it at the same moment it would otherwise fill in inputRef.current: right after putting the element on the page.
Both ways side by side. The middle column is a ref object, the right one a callback ref:
| Ref object | Callback ref | |
|---|---|---|
| what goes into ref | ref={inputRef} | ref={(node) => …} |
| the element is created | React does inputRef.current = element | React calls your function with the element |
| where the element is stored | in current, by itself | wherever you store it |
| good for | one element | a list of elements whose number changes |
Step 2: the key rack with labels is a Map. A Map is a built-in collection of key → value pairs. It's similar to an object, but it's made for adding and removing often and has clear methods for it:
const hooks = new Map() // an empty rackhooks.set('Tom', 'key A') // hang "key A" on the hook labelled Tomhooks.get('Tom') // → 'key A' (look at what hangs on the Tom hook)hooks.get('Salem') // → undefined (there's no such hook)hooks.delete('Tom') // take off whatever hangs on the Tom hook
The rack has to last between renders and changing it shouldn't re-render anything – that's exactly the memory without a render from section 1. So you keep the Map in a ref:
// at the top of the component with the list (you'll see all of it in step 3)// <string, HTMLLIElement>: the labels are strings (cat names), <li> elements hang on the hooksconst itemsRef = useRef(new Map<string, HTMLLIElement>())
Step 3: put it together. Every <li> gets its own function that hangs its element on the rack under the cat's name:
function CatList() {const itemsRef = useRef(new Map<string, HTMLLIElement>()) // the rack in the drawerfunction scrollTo(name: string) {// take the key off the hook and scroll to the element; ?. in case nothing hangs there.// behavior: 'smooth' = scroll smoothly, not in one jumpitemsRef.current.get(name)?.scrollIntoView({ behavior: 'smooth' })}return (<><button onClick={() => scrollTo('Tom')}>→ Tom</button><ul>{cats.map((cat) => (<likey={cat}ref={(node) => {if (node) itemsRef.current.set(cat, node) // the element was created → hang it under the cat's name}}>🐱 {cat}</li>))}</ul></>)}
What happens, step by step:
CatList(). map creates eight <li> and one function in ref for each. The rack is still empty.set, so eight elements hang on the rack.scrollTo('Tom') calls get('Tom'), gets the <li> with Tom and calls its scrollIntoView.How does each function know which name to hang the element under? It was created inside map for one particular cat and remembers the cat variable – it's a closure from JavaScript 02. And what is the condition if (node) good for? React calls the function again with null when the element leaves the page. null doesn't belong on the rack – and right below you'll see a better way to handle it.
Cleanup: when a cat disappears. When you remove Tom from the list, his <li> leaves the page, but the element still hangs on the rack – a key to a demolished door. That's why the function in ref can return a cleanup, just like an effect in Hooks 01 (pack up the camp before you leave). React calls it when the element disappears:
// an attribute of the <li> element inside map in CatList above – it replaces the ref={…} thereref={(node) => {if (node) itemsRef.current.set(cat, node) // the element was created → hang it on the rackreturn () => {itemsRef.current.delete(cat) // the element is gone → take it off the rack}}}
When the function returns a cleanup, React no longer calls it with null. The if (node) stays only for TypeScript, which doesn't know that and types node as HTMLLIElement | null. Returning a cleanup from a ref works since React 19. In older code you'll see a branch for null instead: if (node) set(…) else delete(…).
A simple rule: one element → useRef; a list of elements → a callback ref and a Map.
What for: when you want to put the cursor into a field hidden inside your own component (<FancyInput />). A ref on the component's tag does nothing by itself – the component has to "pass it on" to its element. How: in React 19 ref is an ordinary prop.
import type { ComponentProps, Ref } from 'react' // two types from React:// Ref<HTMLInputElement> = the type of a ref to a field// ComponentProps<'input'> = all the props of an ordinary <input>; & = joins two types: the props must have the properties of bothfunction MyInput({ ref, ...props }: { ref?: Ref<HTMLInputElement> } & ComponentProps<'input'>) {return <input ref={ref} {...props} /> // pass the ref on to the real field, the other props too}// Use – as if it were an ordinary <input>const inputRef = useRef<HTMLInputElement>(null)<MyInput ref={inputRef} placeholder="Search…" />
...props in the parameter collects all the other props into one object, and {...props} spreads them onto the <input> again (rest and spread from lesson JavaScript 10). In other people's code you'll also meet the older forwardRef from React 18 – it does the same.
When you hand the parent the whole field, it can do anything with it: change styles, delete the content, add listeners. It's like giving someone a TV together with a screwdriver. Often it's better to give them just a remote control with a few buttons. That's what useImperativeHandle is for:
import { useImperativeHandle, useRef, type Ref } from 'react'// The remote's buttons – what the parent may callinterface FancyInputHandle {focus: () => voidshake: () => void}function FancyInput({ ref }: { ref?: Ref<FancyInputHandle> }) {const inputRef = useRef<HTMLInputElement>(null) // its own, private ref to the field// "Don't put the field into the parent's ref, put this object with two functions there."useImperativeHandle(ref, () => ({focus: () => inputRef.current?.focus(),shake: () => { /* a short shaking animation */ },}))return <input ref={inputRef} />}// The parent sees just the remote's two buttons:const emailRef = useRef<FancyInputHandle>(null)emailRef.current?.shake()
What you see: The FancyInput component from the example above. The parent has two buttons that call the functions of its "remote".
Try it:
useImperativeHandle. The parent never gets the <input> itself.The takeaway: The component decides what it lets the parent control. A small, clear API is safer than handing over the whole element.
Loading the interactive part…
This section puts the lesson together into steps to come back to when you write your own code. You'll find the same pattern in the Cheat sheets on the React tab.
import { useRef, type ComponentProps, type Ref } from 'react'// ─── 1. MEMORY WITHOUT A RENDER: a timer's number ───────────function Timer() {const timerRef = useRef(0) // a drawer for the timer's number (0 = none running)function start() {// tick = a made-up function the timer should call every secondtimerRef.current = window.setInterval(tick, 1000) // store the number – nothing re-renders}function stop() {clearInterval(timerRef.current) // take the number out and stop the timer}return (<><button onClick={start}>Start</button><button onClick={stop}>Stop</button></>)}// ─── 2. A REF TO AN ELEMENT ON THE PAGE: the cursor into a field ─function EditName() {const inputRef = useRef<HTMLInputElement>(null) // the element's type; null = no element yetfunction focusIt() {inputRef.current?.focus() // ?. = if there's no element yet, do nothing}return (<><input ref={inputRef} /> {/* React stores the element here after rendering */}<button onClick={focusIt}>Edit</button></>)}// ─── 3. REFS TO THE ELEMENTS OF A LIST: a callback ref + a Map ─function NameList({ names }: { names: string[] }) {// a coat rack in the drawer: name → <li> elementconst itemsRef = useRef(new Map<string, HTMLLIElement>())function scrollTo(name: string) {itemsRef.current.get(name)?.scrollIntoView() // find the element by name and scroll to it}return (<><button onClick={() => scrollTo('Tom')}>→ Tom</button><ul>{names.map((name) => (<likey={name}ref={(node) => {if (node) itemsRef.current.set(name, node) // the element was created → hang it on the rackreturn () => { itemsRef.current.delete(name) } // the element is gone → take it down}}>{name}</li>))}</ul></>)}// ─── 4. A REF PASSED ON FROM YOUR OWN COMPONENT (React 19) ──// ref is an ordinary prop; ...props collects the other props and {...props} passes them to the fieldfunction MyInput({ ref, ...props }: { ref?: Ref<HTMLInputElement> } & ComponentProps<'input'>) {return <input ref={ref} {...props} />}// use: <MyInput ref={inputRef} placeholder="Search…" />
ref.current only in event handlers and effects, not during render.null (?.) until the element exists.document.querySelector (a browser function that searches the whole page for an element – it goes around React).Two steps from the template in section 2: attach the ref to the field and call focus in the click handler.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The chat practises sections 1 and 2: a ref to an element on the page (scrolling, focus) and a ref as memory without a render. The countdown practises section 3 – you'll design your own remote control. For every value, first tell yourself: is it visible, or is it just for the code?
A combination of a ref to an element on the page, a ref as memory without a render and an effect that syncs the scrolling. What exactly should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
Design a component with a remote of three buttons (start, pause, reset) – exactly how video players in component libraries work. What exactly the countdown should do is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
?..ref, React calls it with the element and you store it in a Map; the returned cleanup deletes it when the element disappears.ref.current during render – only in event handlers and effects.useImperativeHandle gives the parent a remote control instead of the whole element.