Hooks 05 · Custom hooks
Custom hooks
How to extract and reuse logic: useLocalStorage, useMediaQuery, useDebounce…
Loading lesson…
Hooks 05 · Custom hooks
How to extract and reuse logic: useLocalStorage, useMediaQuery, useDebounce…
Loading lesson…
We want to show in the header whether the user is online. The browser knows (navigator.onLine is true or false) and on a change it sends an online or offline event. With an effect from lesson Hooks 01 you can write it:
function StatusBar() {const [isOnline, setIsOnline] = useState(navigator.onLine) // the initial value from the browseruseEffect(() => {const goOnline = () => setIsOnline(true)const goOffline = () => setIsOnline(false)window.addEventListener('online', goOnline) // set up camp: listenwindow.addEventListener('offline', goOffline)return () => { // pack up camp: stopwindow.removeEventListener('online', goOnline)window.removeEventListener('offline', goOffline)}}, [])return <p>{isOnline ? '🟢 Online' : '🔴 Offline'}</p>}
Then a request comes along: the "Save" button should be disabled without a connection. The button is another component. What now?
SaveButton. Fifteen lines twice.StatusBar. You forget the copy in SaveButton – and the two copies start behaving differently.SaveButton suddenly holds browser event listeners, although it wants to know just one thing: "am I online?"You know how to share components – they're functions. But state and effects are so far nailed inside a component. A custom hook is a way to pull a combination of hooks out into a separate function and use it in as many components as you like: const isOnline = useOnlineStatus().
Béchamel sauce is in the cookbook only once, but it's used in lasagne, in potato gratin and in many other dishes. The lasagne recipe doesn't describe again how to make a roux. It just says "make a béchamel (p. 12)". The recipe is shorter and more readable, and when the béchamel method improves, it improves in every dish at once.
A custom hook is such a basic recipe: a function named use… that calls other hooks inside (state, an effect, a ref, a context) and returns what the component needs.
The table shows typical situations; on the right is whether a hook suits them:
| Situation | A custom hook? |
|---|---|
| the same combination of state and an effect in two or more components | ✅ yes – write it once |
| a long component mixing "what to show" with "how to find it out" | ✅ yes – name that part (useChatRoom) |
| a function that only calculates (formatPrice) and calls no hook | ❌ no – an ordinary function without use |
| two components should see the same data (one cart) | ❌ a hook alone isn’t enough – Context or a store (shared state kept outside components, lesson Advanced React 09) |
The last row is the most common mistake, which is why it has its own heading in section 1: a hook shares the method, not the data.
Every custom hook is written to the same pattern. We'll show it twice: first in general and then filled in as the hook useOnlineStatus for the online status from the introduction.
// ─── THE NAME starts with use ────────────────────────────// That's how React (and the tools in your editor) know there are hooks inside.function useSomething(param: ParamType) {// ─── 1. THE HOOKS THAT WERE REPEATING ──────────────────// Take them out of the component and put them here – unchanged.const [value, setValue] = useState(initialValue)useEffect(() => {/* … set up camp, return the cleanup … */}, [param])// ─── 2. WHAT THE COMPONENT NEEDS ───────────────────────// A value, a pair [value, function] or an object.return value}// Use – in as many components as you like:const value = useSomething(param)
Three questions come with a hook:
The answers for the online status: what repeats is the state with the effect, the hook needs nothing from outside, the component wants true/false back.
function useOnlineStatus() {// 1. the hooks taken out of StatusBar – unchangedconst [isOnline, setIsOnline] = useState(navigator.onLine)useEffect(() => {const goOnline = () => setIsOnline(true)const goOffline = () => setIsOnline(false)window.addEventListener('online', goOnline)window.addEventListener('offline', goOffline)return () => {window.removeEventListener('online', goOnline)window.removeEventListener('offline', goOffline)}}, [])// 2. the component needs just true/falsereturn isOnline}
function StatusBar() {const isOnline = useOnlineStatus()return <p>{isOnline ? '🟢 Online' : '🔴 Offline'}</p>}function SaveButton() {const isOnline = useOnlineStatus()return <button disabled={!isOnline}>{isOnline ? 'Save' : 'Waiting for a connection…'}</button>}
The components now read like a sentence: "find out whether I'm online and show yourself accordingly". How it's found out is hidden in the "recipe on p. 12". You fix a bug in the effect in one place and it's fixed everywhere.
An important detail: when you cook lasagne and potatoes at the same time, they don't share one pot of béchamel. Each dish makes its own sauce by the same recipe. Hooks are the same: StatusBar and SaveButton each have their own useState and their own effect with its own listeners. The values agree only because both listen to the same browser – not because they share state.
So a hook shares the method (the logic), not the pot (the state). When two components should see the same data (one cart), you need state in the parent (lesson React basics 04), Context (lesson Hooks 04) or a store (lesson Advanced React 09).
What for: a half-written note, the chosen theme, the font size – things that shouldn't disappear after reloading the page (F5). The hook behaves like useState but also saves the value to the browser's localStorage (lesson JavaScript 08).
function useLocalStorage<T>(key: string, initialValue: T) {// 1) Lazy initialisation (lesson React basics 03): we read the storage only on the first renderconst [value, setValue] = useState<T>(() => {const stored = localStorage.getItem(key) // a text, or nullreturn stored !== null ? JSON.parse(stored) : initialValue // JSON.parse = text → value})// 2) An effect: after every change, write the value to the storageuseEffect(() => {localStorage.setItem(key, JSON.stringify(value)) // JSON.stringify = value → text}, [key, value])// 3) Return the same pair as useState (as const is explained in the FAQ below)return [value, setValue] as const}// Use – it looks exactly like useState:const [note, setNote] = useLocalStorage('note', '')
useState looks into the storage. If something is there (from a previous visit), it uses that; otherwise the initial value.setNote changes the state, the component re-renders and the effect writes the value to the storage.The demo's code is longer than the version above by two safety nets. Reading and writing are wrapped in try/catch (lesson JavaScript 08): the storage may hold a broken text that JSON.parse fails on, or it may be full or blocked – and the page shouldn't stop working because of that. And JSON.parse(stored) as T tells TypeScript "trust me, the saved value has the same type as the initial one" – JSON.parse itself can't know what comes out of the text. The second hook, useToggle, returns three things: the value, a function that flips it and setOn for when you want to set true or false directly. The component unpacks only the first two – you may leave out the rest of the array.
What you see: A note field and a font size – both use useLocalStorage. The preview button uses a second small hook, useToggle, which returns a value and a function to toggle it.
Try it:
useToggle saves nothing, it's ordinary state.The takeaway: The component uses useLocalStorage just like useState. That the value is saved is hidden in the hook.
Loading the interactive part…
You know two rules of hooks from lesson React basics 03:
if, a loop or a nested function.A reminder of why the second one: React writes a component's state into its notebook one below the other – line 1, line 2… It doesn't see the variable names, so it can tell which line belongs to which hook only by the order of the calls. When a hook is called one time and not the next, all the hooks below it get someone else's line – the age would suddenly read the name.
Why come back to the rules right here? A custom hook is just a function the component calls. The hooks inside it therefore write into that component's notebook, as if they stood right in it. Two things follow: the rules apply inside the hook, and they apply to calling the hook itself too – useLocalStorage hidden in an if shifts the lines exactly like useState in an if. On top of that come two new things React basics didn't cover: the trap called an early return and the one exception to the rules.
An early return is a condition too. A hook below it gets called once and not the next time – the same bug as a hook in an if, just harder to see:
// User = a made-up type of the signed-in user// ❌ not like thisfunction Profile({ user }: { user: User | null }) {if (!user) return <p>You're not signed in.</p> // an early return…const [tab, setTab] = useState('info') // …this hook is then called only for a signed-in userreturn <p>{user.name}: {tab}</p>}// ✅ like this – hooks at the top, the return with a condition below themfunction Profile({ user }: { user: User | null }) {const [tab, setTab] = useState('info') // called on every renderif (!user) return <p>You're not signed in.</p>return <p>{user.name}: {tab}</p>}
All the rules together – the rule on the left, why it holds on the right:
| Rule | Why |
|---|---|
| Call hooks only at the top level – not in conditions, loops, after an early return | React pairs state with hooks by the order of calls. A different order = someone else’s line of the notebook. |
| Call them only from components and other hooks | Outside rendering React doesn’t know whose notebook to open. |
The name starts with use | The tools in your editor (the ESLint linter) recognise a hook by it and check the rules and dependencies. |
An exception: use() | The use() hook (reads a Context or a Promise, lesson Hooks 04) doesn’t take up any line in the notebook – it just reads a value. That’s why it may be inside a condition. |
Some values don't belong to React but to the browser: is the user online? How wide is the window? Is the system in dark mode? React doesn't have them in its state, and they change without anyone asking it. So a component needs two things:
In section 1 we solved this with state and an effect. But React has a ready-made hook for exactly this situation: useSyncExternalStore. Step by step we'll rewrite useOnlineStatus with it – and the components that use it won't change by a single letter.
You want to keep up with the news. You could copy the newspaper into a notebook every morning – but that's extra work and the copy can be out of date. A subscriber does it more cleverly:
useSyncExternalStore is that kind of subscriber. You write it two short functions – one for each point above:
getSnapshot – a look in the letterbox: returns the value that holds right now.subscribe – the agreement about ringing: says on which browser event React should be rung.You can read the hook's name in parts: use (a hook) + sync (synchronised – always up to date) + external store (anything outside React that holds a value; here the browser).
function getSnapshot() {return navigator.onLine // true = online, false = offline}
That's all. The function just returns the value the browser knows. React calls it every time it needs to know what holds – on every render of the component.
When the connection changes, the browser fires the online or offline event. We hang the bell React gives us on both:
function subscribe(onChange: () => void) {// onChange = a bell from React. You just hang it on browser events:window.addEventListener('online', onChange) // the connection came back → it ringswindow.addEventListener('offline', onChange) // the connection dropped → it rings// the cleanup: when the component disappears, React calls this function and the bell comes downreturn () => {window.removeEventListener('online', onChange)window.removeEventListener('offline', onChange)}}
Two things here puzzle almost everyone:
onChange come from when you never write it? You don't write it. React calls your subscribe function and passes onChange to it as a parameter – much like React passes the event e to the function you put in onClick. You just hang it on the events. When the browser then calls it, for React it means: "something changed, look in the letterbox again".return with a function at the end for? It's the cleanup, the same as in an effect: packing up the camp when you leave (lesson Hooks 01). Without it the bell would stay hanging even after the component is gone.function useOnlineStatus() {return useSyncExternalStore(subscribe, getSnapshot)}
You only hand both functions to the hook – without parentheses. You don't call them; React calls them when it needs to. It's the same as a callback in setTimeout(fn, 1000) (lesson JavaScript 02). useSyncExternalStore then returns what getSnapshot returned – that is true or false – and the hook passes it on to the component.
Now let's put it all together. The hook and both its functions belong in one file, say src/hooks/useOnlineStatus.ts (without JSX the .ts extension is enough). The component is in its own file and imports the hook (import/export from lesson JavaScript 08):
// ═══ FILE src/hooks/useOnlineStatus.ts ═════════════════════════import { useSyncExternalStore } from 'react'// Step 2 and step 1: at the top of the file, OUTSIDE the hook function, no exportfunction subscribe(onChange: () => void) {window.addEventListener('online', onChange)window.addEventListener('offline', onChange)return () => {window.removeEventListener('online', onChange)window.removeEventListener('offline', onChange)}}function getSnapshot() {return navigator.onLine}// Step 3: the hook below them, with export – the only thing the file offers outsideexport function useOnlineStatus() {return useSyncExternalStore(subscribe, getSnapshot)}// ═══ FILE src/components/StatusBar.tsx (from section 1, unchanged) ═══import { useOnlineStatus } from '../hooks/useOnlineStatus' // imports just the hookexport function StatusBar() {const isOnline = useOnlineStatus() // true or falsereturn <p>{isOnline ? '🟢 Online' : '🔴 Offline'}</p>}
Why exactly like this:
subscribe and getSnapshot are outside the hook. They don't need anything from the hook (no parameter or variable), so they don't have to be inside. And outside the hook they're created only once, when the file loads – inside, they'd be created anew on every render (the box below says why that's a problem).A simple rule: what doesn't need anything from the hook goes above the hook in the same file.
useOnlineStatus(). React calls getSnapshot, gets true and the component shows 🟢.subscribe and hands it the onChange bell. The bell now hangs on the online and offline events.offline event → the bell rings → React calls getSnapshot and gets false. That's a different value than last time, so it re-renders the component and it shows 🔴.subscribe returned, and the bell comes down.Compared with section 1, the hook has no useState, no useEffect and no calls of setIsOnline. The hook remembers nothing – it only says where to find the value and how to learn about a change. And StatusBar and SaveButton didn't change: that's the swap in one place from section 1.
The shared-state libraries Zustand and Redux (lesson Advanced React 09) and this course's navigation stand on the same principle: they all keep a value outside React and components subscribe to it.
The demo has three hooks following the same pattern: useOnlineStatus from the example above, useWindowWidth (the resize event when the window size changes, the value window.innerWidth – the window width in pixels) and useMediaQuery. That one asks the browser through window.matchMedia(query) whether a condition about the screen, written as in CSS, holds – say "the window is at least 900 px wide" or "the system is in dark mode".
What you see: Three hooks built on useSyncExternalStore: the window width, the system theme (through matchMedia – a browser function that asks about the screen's properties, dark mode say) and the connection status.
Try it:
The takeaway: Every line is one line of code in the component. The subscription, the cleanup and reading the current value are hidden in the hook.
Loading the interactive part…
So far every hook solved one specific thing: the online status, the window width, saving to the storage. But a hook can also be general. Think of a cookbook: the recipe "fruit cake" describes the dough and the baking once, and you pick the fruit yourself – apples, plums, blueberries. The steps are the same; only one ingredient differs.
That's exactly how it is with loading data. Loading a user, a list of products or orders – the same steps every time; only one thing differs: what gets loaded. We'll turn that one thing into a parameter of the hook.
You know loading with async/await from the recipe in lesson Hooks 01: a state for the data, a state for the error, an effect with ignore against the race of responses and try/catch for errors. About twenty lines. When the app loads users and products, you write them twice – and the two copies differ in a single line:
// in the Profile component:const data = await fetchUser(userId) // ← the only different line// in the ProductList component:const data = await fetchProducts() // ← the only different line// (fetchUser and fetchProducts = made-up functions that ask the server for data and return a Promise)
So the three questions from section 1 have these answers:
ignore and try/catch.userId changes).Loading is always in one of three states: loading, done, or error. Instead of two separate states (data and error) we'll describe them with one type – a discriminated union from lesson TypeScript 02:
// T = the type of the loaded data (a user, an array of products…) – TypeScript fills it in itselftype AsyncState<T> =| { status: 'loading' } // loading – nothing yet| { status: 'success'; data: T } // done – only here is there data| { status: 'error'; error: Error } // error – only here is there an error
The status property says which state we're in. The advantage: nonsense like "I have data and an error at the same time" can never happen – each state has only what belongs to it.
Now we take the recipe from Hooks 01 and replace the single changing line with a parameter load:
// load = a function that loads and returns a Promise (the component supplies this "ingredient")// deps = an array of dependencies: when to load again (the same as useEffect's second parameter)function useAsync<T>(load: () => Promise<T>, deps: unknown[]) {const [state, setState] = useState<AsyncState<T>>({ status: 'loading' })useEffect(() => {let ignore = false // "I still want this response"setState({ status: 'loading' }) // a new load → back to "loading"async function run() {try {const data = await load() // ← this used to be fetchUser(userId)if (!ignore) setState({ status: 'success', data })} catch (err) {// err as Error = "trust me, it's an error" (as from the Glossary in lesson TypeScript 01)if (!ignore) setState({ status: 'error', error: err as Error })}}run()return () => {ignore = true // the cleanup: throw away a late response}}, deps) // when to load again, the component saysreturn state // one of the three states from step 1}
There's nothing new inside – it's the recipe from Hooks 01, only instead of two states it has one state, and instead of fetchUser(userId) it calls load(). The hook doesn't know, and doesn't need to know, whether it's loading a user or products.
function UserCard({ id }: { id: number }) {const user = useAsync(() => fetchUser(id), [id]) // what to load and when again// pick what to show by the statusif (user.status === 'loading') return <p>Loading…</p>if (user.status === 'error') return <p>{user.error.message}</p> // .message = the error's textreturn <p>{user.data.name}</p> // only 'success' is left → there is data}
() => fetchUser(id) and not just fetchUser(id) without the arrow? fetchUser(id) would start loading right now, on every render. The arrow is a function "when you want to, load user id" – and the hook calls it itself in its effect. Just like in section 4: you only hand over the function, someone else calls it.[id] for? It tells the hook: "load again when id changes". Why the component has to say it is explained in the paragraph below.user.data.name straight away on the last line? After two ifs with return only the success state is left – and TypeScript knows it (narrowing from lesson TypeScript 02). If you touched user.data earlier, it would report an error.The component now deals only with what to load and how to show it. How the loading works is hidden in the hook – and another component (products, orders) uses the same hook with a different ingredient.
One thing here looks like breaking the rule "don't lie about dependencies" from lesson Hooks 01: the effect calls load, but its dependencies are deps, not [load]. Why?
The arrow () => fetchUser(id) is created anew on every render of the component – it's a different function each time, even though it does the same thing. With [load] the effect would see a "change" on every render and load again. But loading itself causes a render (by changing the state), that creates a new arrow, that another load… and so on forever.
That's why the hook leaves it to the component to say what its function really depends on: [id]. id changes → it loads again; otherwise not. TanStack Query (lesson Advanced React 08) uses the same principle with its queryKey.
What you see: Two UserCard cards, both using useAsync. The left one loads a user according to the button, the right one always has user no. 1.
Try it:
error state from the hook.The takeaway: One loading recipe, every use with its own ingredient and its own state.
Loading the interactive part…
This section puts the lesson together into steps to come back to when you write your own hook. You'll find the same pattern in the Cheat sheets on the React tab.
useState, useEffect, useRef, use)? If not → an ordinary function without use in its name.// the file src/hooks/useNow.ts – a hook without JSX can have the .ts extension// (the clock from lesson Hooks 01, moved into a hook)import { useEffect, useState } from 'react'// A name by PURPOSE, not by when it runs (useNow, not useOnMount)// ms = after how many milliseconds the time refreshesexport function useNow(ms: number) {// 1. the hooks that would otherwise repeatconst [now, setNow] = useState(() => new Date()) // the current time; lazy initialisation (React basics 03)useEffect(() => {const id = setInterval(() => setNow(new Date()), ms) // set up: a new time every ms millisecondsreturn () => clearInterval(id) // pack up: stop the interval}, [ms]) // where I'm camping// 2. what the component needsreturn now}// use: const now = useNow(1000) → <p>{now.toLocaleTimeString()}</p>
For inspiration – each of them is a few lines following the template above:
useDebounce(value, ms) // a value that changes only after a quiet momentuseLocalStorage(key, init) // state saved in the browseruseMediaQuery(query) // does a condition about the screen hold (window width, dark mode)?useInterval(fn, ms) // a repeating timer with its cleanupusePrevious(value) // the value from the previous renderuseOnClickOutside(ref, fn) // a click outside an element – closing a menu or a dialoguseCopyToClipboard() // copying text to the clipboarduseIntersectionObserver(ref) // is the element on screen right now?useAuth() // the signed-in user from context (lesson Hooks 04)
Before you write your own, have a look at the libraries usehooks-ts or @uidotdev/usehooks. But writing them yourself once is the best way to understand effects.
use and there really is a hook inside.useChatRoom), not the moment it runs (useMount).Write the body of a simple custom hook. Two checkboxes will then work independently of each other – each has its own pot.
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…
You make the search logic from lesson Hooks 01 reusable – the whole hook is about 8 lines. What should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
You finish the useLocalStorage hook from section 2 and the form starts remembering the name and the tick after a page reload. What goes where 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.
use… function that calls other hooks and hides repeating logic.products)products – from the file src/course/fakeApi.en.ts. The course fake API: data and functions pretending to be a server (with a delay, sometimes even with an error). In a real app you would call fetch() here.export interface Product {id: numbername: stringcategory: 'fruit' | 'vegetables' | 'bakery' | 'dairy'price: numberinStock: boolean}export const products: Product[] = [{ id: 1, name: 'Apple', category: 'fruit', price: 12, inStock: true },{ id: 2, name: 'Banana', category: 'fruit', price: 8, inStock: true },{ id: 3, name: 'Pear', category: 'fruit', price: 15, inStock: false },{ id: 4, name: 'Carrot', category: 'vegetables', price: 6, inStock: true },{ id: 5, name: 'Tomato', category: 'vegetables', price: 9, inStock: true },{ id: 6, name: 'Cucumber', category: 'vegetables', price: 19, inStock: false },{ id: 7, name: 'Bread roll', category: 'bakery', price: 3, inStock: true },{ id: 8, name: 'Bread', category: 'bakery', price: 45, inStock: true },{ id: 9, name: 'Milk', category: 'dairy', price: 22, inStock: true },{ id: 10, name: 'Cheddar', category: 'dairy', price: 39, inStock: true },{ id: 11, name: 'Yogurt', category: 'dairy', price: 14, inStock: false },{ id: 12, name: 'Orange', category: 'fruit', price: 11, inStock: true },]
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).