Custom hooks
A custom hook is a normal function whose name starts with use and which calls other hooks. It lets you write stateful logic like fetching, localStorage sync or debouncing once and reuse it in any component with one line; it shares logic, not state.
38.1 The problem: the same logic in every component
- Products keeps data and error states and fetches /api/products in useEffect, with the alive flag race-condition fix from useEffect part 2.
- The screen shows Loading..., then 3 products.
- When Users and Orders need the same thing, all these lines get copy-pasted.
React (JSX)
function Products() { const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { let alive = true; fetch("/api/products") .then((res) => res.json()) .then((d) => alive && setData(d)) .catch((e) => alive && setError(e)); return () => { alive = false; }; }, []); if (error) return <p>{error.message}</p>; if (!data) return <p>Loading...</p>; return <p>{data.length} products</p>;}Output
Loading...3 products38.2 Why are custom hooks used?
- Copied in three places, one bug fix means changing three places; miss one and the bug stays.
- Components get long and the real UI logic hides under fetch code.
- We need the logic in one place and usable in every component with a single line.
38.3 Fix: the useFetch custom hook
- useFetch(url) holds the same two states and the same useEffect; the fixed URL becomes the url parameter.
- url is in the dependency array, so data is fetched again when the url changes.
- It returns { data, error, loading } in one object (loading = !data && !error).
JavaScript
export function useFetch(url) { const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { let alive = true; fetch(url) .then((res) => res.json()) .then((d) => alive && setData(d)) .catch((e) => alive && setError(e)); return () => { alive = false; }; }, [url]); const loading = !data && !error; return { data, error, loading };}38.4 Using it in one line
- Products calls useFetch("/api/products") and destructures data, error, loading; the rest is only UI.
- Users uses the same hook in one line.
- A bug fix now happens in just one file.
React (JSX)
import { useFetch } from "./useFetch"; function Products() { const { data, error, loading } = useFetch("/api/products"); if (loading) return <p>Loading...</p>; if (error) return <p>{error.message}</p>; return <p>{data.length} products</p>;} function Users() { const { data } = useFetch("/api/users"); return <p>{data?.length ?? 0} users</p>;}Output
Loading...0 users-- responses arrive --3 products2 users- Step 1
1.useFetch(url) written once in useFetch.js
- Step 2
2.Products calls useFetch("/api/products")
- Step 3
3.Users calls useFetch("/api/users")
- Step 4
4.Each call runs its own useState + useEffect
- Step 5
5.Each component gets its own { data, error, loading }
Every call = new state
38.5 Logic is shared, state is not
- A custom hook shares logic, not state.
- Each call to useFetch creates separate state for that component, exactly as if you wrote those lines in the component yourself.
- Checkpoint: two Counters A and B use useCounter; clicking A three times gives A: 3, B: 0.
- To really share data, lift the state up or use Context.
React (JSX)
function useCounter() { const [count, setCount] = useState(0); const inc = () => setCount((c) => c + 1); return [count, inc];} function Counter({ label }) { const [count, inc] = useCounter(); return ( <button onClick={inc}> {label}: {count} </button> );}// App: Counter A and Counter BOutput
[button] A: 0[button] B: 0-- click A three times --[button] A: 3[button] B: 038.6 useLocalStorage
- Keeps state that survives a page refresh, like the theme or language.
- useState gets a function (lazy initializer) that runs only on the first render and reads the saved value from localStorage if there is one.
- useEffect saves JSON.stringify(value) on every change; the hook returns [value, setValue] like useState.
- Switch the theme to dark and refresh: it stays dark.
JavaScript
export function useLocalStorage(key, init) { const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : init; }); useEffect(() => { const json = JSON.stringify(value); localStorage.setItem(key, json); }, [key, value]); return [value, setValue];} // use: const [theme, setTheme] =// useLocalStorage("theme", "light");Output
[button] Theme: light-- click --[button] Theme: dark-- refresh the page --[button] Theme: darkStill dark after refresh38.7 useDebounce
- Typing "shoes" with an API call per letter sends five calls when only the final word is needed.
- useDebounce(value, delay) sets a timer in useEffect and updates the debounced value only after the delay.
- If the value changes in between, the cleanup clears the old timer, so the value updates only when typing stops.
JavaScript
export function useDebounce(value, delay) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => { setDebounced(value); }, delay); return () => clearTimeout(id); }, [value, delay]); return debounced;}- Step 1
1.User types "s": effect starts a 500ms timer
- Step 2
2.Types "h" before 500ms: cleanup clears the old timer, new timer starts
- Step 3
3.... same for "o", "e", "s"
- Step 4
4.User stops: 500ms passes, setDebounced("shoes")
- Step 5
5.query changes once: one API call
5 keystrokes, 1 call
38.8 useDebounce in a SearchBox
- text updates on every keystroke; query = useDebounce(text, 500) changes only after a 500ms pause.
- The effect depends only on query, so typing shoes quickly logs one search.
- Without debounce, the same typing sends five calls: less server load and a faster-feeling app.
React (JSX)
function SearchBox() { const [text, setText] = useState(""); const query = useDebounce(text, 500); useEffect(() => { if (query) console.log("Search:", query); }, [query]); return ( <input value={text} onChange={(e) => setText(e.target.value)} /> );}Output
Input: empty-- type "shoes" quickly --Input: shoesConsole: Search: shoes38.9 Comparison: the three hooks
| Hook | Job | Returns | Built from |
|---|---|---|---|
| useFetch(url) | Fetch data with loading/error and race-condition guard | { data, error, loading } | useState x2 + useEffect |
| useLocalStorage(key, init) | State that survives a refresh | [value, setValue] | useState (lazy init) + useEffect |
| useDebounce(value, delay) | Update a value only after typing stops | debounced value | useState + useEffect with cleanup |
38.10 Common mistakes
- Naming a hook without use (getUser) while calling useState inside: the React lint plugin errors because it cannot tell it is a hook.
- Fix: start the name with use (useUser) so lint checks the rules of hooks and readers know too.
React (JSX)
// Wrong: normal name, hook inside -> lint errorfunction getUser(id) { const [user, setUser] = useState(null); // ...fetch logic return user;}React (JSX)
// Right: name starts with "use" -> rules of hooks get checkedfunction useUser(id) { const [user, setUser] = useState(null); // ...fetch logic return user;}- Myth: "a custom hook is a special API that must be registered". It is a normal function; it is a hook only because it calls hooks like useState or useEffect.
- If a function calls no hook (e.g. formatting a price), keep it a normal function.
38.11 Rules of custom hooks
- Always start the name with use; call it only at the top level of a component or another hook, never inside an if or a loop.
- One hook, one job: useFetch only fetches, useDebounce only debounces.
- Return shape: two values in an array (like useState), more values in an object (data, error, loading).
38.12 Interview tips
- A custom hook is a JavaScript function whose name starts with use and which uses other hooks inside.
- Its purpose is reusing stateful logic between components: data fetching, localStorage sync, debouncing.
- It shares logic, not state: every call gets its own state.
- The rules of hooks apply to custom hooks too.