React / 47
Custom hooks
A function whose name starts with use and that calls other hooks. It lets components share stateful logic, like online status or fetching, without sharing state.
A hook is just a function that calls hooks
import { useEffect, useState } from "react";
export function useOnlineStatus() {
const [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);
};
}, []);
return isOnline;
}Now any component gets the feature in one line:
import { useOnlineStatus } from "../hooks/useOnlineStatus";
function StatusBar() {
const isOnline = useOnlineStatus();
return <p>{isOnline ? "Online" : "Offline: changes will sync later"}</p>;
}StatusBar no longer knows how online status is detected, just that it can ask. That's single responsibility again: the hook owns the logic, the component owns the UI.
The rules
| Rule | Why |
|---|---|
Name it use + a capital letter: useOnlineStatus, not onlineStatus or useonline | The lint rules and the React Compiler use the name to know it's a hook and check the rules inside it. |
Call hooks only at the top level, never inside if, loops or nested functions | React matches each useState to its stored value by call order. Skipping one on some renders shifts every hook after it. |
| Call hooks only from components or other hooks | Hooks need a component render to attach their state to. A regular function or event handler doesn't have one. |
If it calls no hooks, don't name it use… | filterVeg(items) is a plain function. The prefix promises "this uses React state". |
Shares logic, not state
This surprises almost everyone the first time. A custom hook is a recipe: each component that calls it cooks its own copy.
hooks/useCounter.js
function useCounter() { const [n, setN] = useState(0) return [n, () => setN(n + 1)]}<LikeButton />
<CartBadge />
One hook, two components
Try it<LikeButton />
calls useCounter()
0
<CartBadge />
calls useCounter()
0
If you do want two components to see the same value, the hook is the wrong tool: lift the state up to a common parent, or put it in context (Chapter 11).
A data hook with cleanup: useFetch
Fetching is the most common custom hook. Here's one that handles loading, errors and a changing URL correctly:
import { useEffect, useState } from "react";
export function useFetch(url) {
const [result, setResult] = useState({ url: null, data: null, error: null });
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => setResult({ url, data, error: null }))
.catch((error) => {
if (error.name !== "AbortError") setResult({ url, data: null, error });
});
return () => controller.abort(); // cancel if url changes or we unmount
}, [url]);
if (result.url !== url) return { data: null, error: null, loading: true };
return { data: result.data, error: result.error, loading: false };
}Two details make it solid:
- Cleanup aborts the request. If
urlchanges or the component unmounts, the old request is cancelled, so a slow, stale reply can never overwrite a newer one. - Loading is worked out, not stored. The result remembers which URL it belongs to. If it's not for the current URL yet, we're loading. No extra
loadingstate to forget to reset.
Hooks can call hooks, so the useMenu from the previous topic is two lines:
import { useFetch } from "./useFetch";
export function useMenu() {
const { data } = useFetch("https://dummyjson.com/recipes?limit=10");
return data?.recipes ?? [];
}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.
