More React Hooks · Lesson 18 of 31
Custom Hooks in React
A custom hook is a JavaScript function whose name starts with use and which calls other hooks. It lets you pull stateful logic – toggling, syncing with localStorage, debouncing, fetching – out of components and reuse it anywhere. Custom hooks are how experienced React teams keep components short and readable.
In this lesson
- Your first custom hook:
useToggle useLocalStorageanduseDebounce- A
useFetchhook with race protection - Rules and what hooks share (logic, not state)
useToggle
import { useCallback, useState } from "react";
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((v) => !v), []); // stable function identity
return [on, toggle];
}
export default function App() {
const [darkMode, toggleDark] = useToggle(false);
const [showHints, toggleHints] = useToggle(true);
return (
<div>
<button onClick={toggleDark}>Dark mode: {darkMode ? "on" : "off"}</button>
<button onClick={toggleHints}>Hints: {showHints ? "on" : "off"}</button>
{showHints && <p>Tip: press / to search lessons.</p>}
</div>
);
}
[Dark mode: off] [Hints: on] Tip: press / to search lessons. › click “Dark mode: off” [Dark mode: on] [Hints: on] Tip: press / to search lessons. › click “Hints: on” [Dark mode: on] [Hints: off]
Each call to useToggle has its own independent state, just like calling useState twice.
useLocalStorage
import { useEffect, useState } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const saved = localStorage.getItem(key);
return saved !== null ? JSON.parse(saved) : initialValue;
} catch {
return initialValue; // corrupted JSON or storage blocked
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
/* storage full or unavailable: keep working in memory */
}
}, [key, value]);
return [value, setValue]; // same shape as useState
}
export default function App() {
const [fontSize, setFontSize] = useLocalStorage("reader-font-size", 16);
return (
<div>
<p>Font size: {fontSize}px</p>
<button onClick={() => setFontSize((s) => s + 2)}>A+</button>
<button onClick={() => setFontSize((s) => s - 2)}>A−</button>
<p>Stored: {localStorage.getItem("reader-font-size")}</p>
</div>
);
}
Font size: 16px [A+] [A−] Stored: › click “A+” Font size: 18px [A+] [A−] Stored: 16 › click “A+” Font size: 20px [A+] [A−] Stored: 18
The "Stored" line lags one step behind because the effect saves the value after each render. Reload the page in a real app and the font size is remembered.
useDebounce
Search-as-you-type shouldn't send a request for every key. Debouncing waits until the user stops typing:
import { useEffect, useState } from "react";
function useDebounce(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id); // a new keystroke cancels the pending update
}, [value, delay]);
return debounced;
}
export default function App() {
const [query, setQuery] = useState("");
const debouncedQuery = useDebounce(query, 300);
return (
<div>
<input aria-label="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
<p>Typed: {query}</p>
<p>Searching for: {debouncedQuery}</p>
</div>
);
}
[] Typed: Searching for: › type “hooks” into Search [hooks] Typed: hooks Searching for: › wait 350ms [hooks] Typed: hooks Searching for: hooks
While you type, "Searching for" stays empty; 300 ms after the last key it catches up. Put debouncedQuery in your fetch effect's dependencies and you get one request instead of five.
useFetch
import { useEffect, useState } from "react";
function useFetch(loader, deps) {
const [state, setState] = useState({ data: null, error: null, loading: true });
useEffect(() => {
let ignore = false;
setState((s) => ({ ...s, loading: true }));
loader()
.then((data) => !ignore && setState({ data, error: null, loading: false }))
.catch((error) => !ignore && setState({ data: null, error: error.message, loading: false }));
return () => { ignore = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
return state;
}
// fake API for the demo
const getLesson = (id) =>
new Promise((resolve) => setTimeout(() => resolve({ id, title: `Lesson ${id}: Custom Hooks` }), 200));
export default function App() {
const [id, setId] = useState(1);
const { data, loading } = useFetch(() => getLesson(id), [id]);
return (
<div>
<button onClick={() => setId((n) => n + 1)}>Next lesson</button>
<p>{loading ? "Loading…" : data.title}</p>
</div>
);
}
[Next lesson] Loading… › wait 250ms [Next lesson] Lesson 1: Custom Hooks › click “Next lesson” [Next lesson] Loading… › wait 250ms [Next lesson] Lesson 2: Custom Hooks
The component is down to two lines of data logic. For production apps, TanStack Query is essentially a much more capable useFetch.
Rules for custom hooks
- Name it useSomething. The prefix tells React's lint rules to check the hook rules inside it.
- Hooks share logic, not state. Two components calling
useToggle()each get their own value. To share the same state, lift it up or use Context. - Follow the rules of hooks inside it: call hooks at the top level, unconditionally.
- Return whatever is convenient – a value, an array like
useState, or an object with named fields. - Don't make every function a hook. If it doesn't call any hooks, it's a regular helper function.
Practice
Try it yourself
Write
useCounter(initial, { min, max })returning{ count, increment, decrement, reset }.Show solution
import { useState } from "react"; function useCounter(initial = 0, { min = -Infinity, max = Infinity } = {}) { const [count, setCount] = useState(initial); return { count, increment: () => setCount((c) => Math.min(max, c + 1)), decrement: () => setCount((c) => Math.max(min, c - 1)), reset: () => setCount(initial), }; } export default function App() { const seats = useCounter(1, { min: 1, max: 3 }); return ( <div> <p>Seats: {seats.count}</p> <button onClick={seats.increment}>Add seat</button> <button onClick={seats.reset}>Reset</button> </div> ); }Seats: 1 [Add seat] [Reset] › click “Add seat” Seats: 2 [Add seat] [Reset] › click “Add seat” Seats: 3 [Add seat] [Reset] › click “Add seat” Seats: 3 [Add seat] [Reset] › click “Reset” Seats: 1 [Add seat] [Reset]
Quick check
Why must a custom hook's name start with use?
So React and its lint rules know it's a hook and enforce the rules of hooks.
Do two components using the same custom hook share state?
No – each call has its own state.
Is a function that doesn't call hooks a custom hook?
No – make it a normal function without the use prefix.
Summary
- Custom hooks are use-prefixed functions that call other hooks to package reusable logic.
- Common ones: useToggle, useLocalStorage, useDebounce, useFetch.
- They share logic, not state; follow the rules of hooks inside them.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.