Refs and Custom Hooks
Reach the DOM and hold values that must not trigger rendering with useRef, then pull repeated hook logic into custom hooks that follow the rules of hooks.
Contentsand lesson path
On this page
- The problem
- Step 1: a ref as a handle on a DOM node
- Step 2: a value that must not trigger rendering
- Step 3: extract the pattern into a custom hook
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Effects & Data Fetching in React
- Effects as Synchronization, Not Lifecycle Concept · 20 min
- Deleting Effects You Do Not Need Worked example · 20 min
- Refs and Custom Hooks Worked example · 20 min
- Fetching Data Safely Inside Components Worked example · 25 min
- Lab: Server State with a Query Cache Lab · 30 min
- Check: Effect and Fetching Bug Hunt Knowledge check · 8 questions
What you will learn
- Extract reusable logic into custom hooks and use refs for DOM access and values that must not trigger re-renders.
Prerequisites: React Components & State, Async JavaScript & Fetch
01. The problem
State is the right home for values the screen shows, but two everyday jobs do not fit it. The first is reaching the DOM: to focus an input, measure an element or play a video, you need the actual node, and React does not give it to you in props or state. The second is remembering a value without rendering: a timer id, the previous value of a prop, a counter used internally — things that must survive between renders, yet should not put a new value on screen when they change.
Both jobs belong to useRef. A ref is a small box React gives you once per component: { current: ... }. Change ref.current and the value persists, silently — no re-render, no re-run. Alongside the two ref jobs, this lesson extracts repeated logic into a custom hook, which is how React projects share behaviour such as debouncing or online status without sharing state. As you read, keep one rule within reach: whatever a ref holds, the UI must not depend on it — if it should show up on screen, it is state.
02. Step 1: a ref as a handle on a DOM node
Pass a ref to the ref attribute of an element and React puts the node into ref.current after it commits the render — before effects run. That timing is why effects and event handlers are the places to use it, and render is not:
import { useRef } from 'react';
export default function FocusSearch() {
const inputRef = useRef(null);
return (
<>
<label>
Search
<input ref={inputRef} type="search" />
</label>{" "}
<button type="button" onClick={() => inputRef.current?.focus()}>
Focus search
</button>
</>
);
}activeElement before the click -> BODY
activeElement after the click -> INPUTThe click handler reads inputRef.current, which by then is the real <input> element, and calls its focus method — plain DOM work, exactly like the DOM skill taught, except React filled the handle in for you. Note the type="button" and the labelled input: the same accessibility rules apply as always. If you need focus to happen on mount rather than on click, that is a synchronisation with the DOM, so it moves into an effect with an empty dependency array — same ref, same call, one run.
03. Step 2: a value that must not trigger rendering
The second job has no DOM in it at all. Here is a component with two counters: one in a ref, one in state. Both buttons work; only one ever redraws the paragraph:
import { useRef, useState } from 'react';
export default function CounterDemo() {
const silentCount = useRef(0);
const [shownCount, setShownCount] = useState(0);
return (
<>
<p>
Silent clicks: {silentCount.current} · Shown clicks: {shownCount}
</p>
<button type="button" onClick={() => { silentCount.current += 1; }}>
Add silently
</button>
<button type="button" onClick={() => setShownCount((c) => c + 1)}>
Add shown
</button>
</>
);
}after 3 silent clicks -> Silent clicks: 0 · Shown clicks: 0
after 1 shown click -> Silent clicks: 3 · Shown clicks: 1Three clicks on "Add silently" changed silentCount.current to 3, and the paragraph kept showing 0 — updating a ref is an ordinary mutation, not an instruction to render. When "Add shown" finally updated state, the re-render happened to show both numbers: 3 and 1. This is the honest picture of a ref: correct and current inside handlers and effects, invisible to the render loop. If a user-visible value ever depends on ref.current, you have built a screen that updates at random-seeming times; move that value to state.
This demo reads silentCount.current during render on purpose, to make the stale value visible. Real code must not: the React Compiler lint rule react-hooks/refs (in the recommended config of eslint-plugin-react-hooks 7) reports exactly that line with "Cannot access refs during render", for the reason the demo shows.
04. Step 3: extract the pattern into a custom hook
Now look at the debouncing you last met in plain JavaScript in the cancellation lesson: wait for a pause before acting. The React version pairs state with an effect and a cleanup, and the whole pattern fits in seven lines. A function that calls other hooks is a custom hook — its name must start with use — and any component can call it as if the lines were pasted in:
import { useEffect, useState } from 'react';
export function useDebouncedValue(value, delayMs) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}import { useState } from 'react';
import { useDebouncedValue } from './use-debounced-value.jsx';
export default function DelayedEcho() {
const [text, setText] = useState('');
const debounced = useDebouncedValue(text, 300);
return (
<>
<label>
Type
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<p>Debounced value: "{debounced}"</p>
</>
);
}type "re", wait 100 ms -> Debounced value: ""
type "react", wait 299 ms -> Debounced value: ""
wait 1 more ms (300 total) -> Debounced value: "react"The transcript shows the two halves working together: while typing continues, each new keystroke re-runs the effect, whose cleanup cancels the pending timer, so the old value holds; once typing pauses for the full 300 ms, the timer survives and the debounced value lands. Note that the timeout id never reaches the UI, so the hook simply closes over it — no ref needed here.
Two properties of custom hooks matter. Each call gets its own state: render DelayedEcho twice and the two echoes lag independently, because a hook shares logic, not state — to share a value, lift it to a common parent or put it in context. And the rules of hooks apply inside them exactly as in components: call hooks unconditionally at the top level of the hook body, never inside conditions, loops or nested functions. The eslint-plugin-react-hooks rule reads custom hooks too, which is why the naming convention exists.
05. Common mistakes
06. Check your understanding
07. Apply it
Two tasks for the book-search practice project:
- Give the search box a "Focus search" button like the one in this lesson, then extend it: move the focus into an effect that runs once on mount, and check the focus order with the keyboard only.
- Extract
useDebouncedValueand use it so that typing fires no request until the user pauses. Then find one more piece of repeated hook logic in your code — a timer, a media query, a persisted value — and extract it the same way. Every hook you write must call hooks only at its top level.
08. Review prompt
Without looking back: what are the two jobs of useRef, and which one would you never show on screen? When does React assign ref.current relative to effects? What must a function satisfy to count as a custom hook, and what does calling it twice in one component give you? And recite the rules of hooks from memory.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.