Skip to main content
Albero Academy

Custom Hooks in Depth

Extract and share stateful logic — the rules, real-world custom hooks (useToggle, useLocalStorage, useFetch) and how to compose them.

Chapter 11React15 min readBeginner friendly
  • #React
  • #Custom Hooks
  • #Reuse

A custom hook is a function whose name starts with use and that calls other hooks. It's how you extract stateful logic out of components to reuse it — the primary way to keep components small and avoid copy-pasting effects and state. This goes well beyond Chapter 3's first taste.

Why custom hooks?

When two components need the same logic (fetching data, reading a media query, syncing with localStorage), you don't duplicate it — you move it into a hook. The component gets a clean one-line call; the messy details live in one testable place.

The rules

  • Name it use… so React's linter can check it and readers know it's a hook.
  • Call hooks only at the top level — never in conditions or loops (this applies inside custom hooks too).
  • A custom hook can return anything — a value, an array (like useState), or an object of values and functions.

Real-world hooks

three you'll actually use
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
return [on, () => setOn(v => !v)];
}
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : initial;
});
useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [key, value]);
return [value, setValue];
}
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize); // cleanup!
}, []);
return width;
}

Composing hooks

Hooks call other hooks, so you build bigger ones from smaller ones:

hooks all the way down
function useDarkMode() {
const [theme, setTheme] = useLocalStorage("theme", "light"); // reuse!
const toggle = () => setTheme(t => t === "light" ? "dark" : "light");
return [theme, toggle];
}

Practice

Write useLocalStorage(key, initial) and use it to persist a form field across refreshes. Build useWindowWidth() with proper cleanup and render a layout that changes above 768px. Then compose a useDarkMode from useLocalStorage.

Key takeaways

  1. 01A custom hook is a use… function that calls other hooks to extract reusable stateful logic.
  2. 02Follow the rules: use… name, hooks at the top level only; return whatever the caller needs.
  3. 03Hooks share logic, not state — each caller gets its own independent state.
  4. 04Always clean up effects (listeners, timers, subscriptions) inside the hook.
  5. 05Compose bigger hooks from smaller ones (useDarkMode from useLocalStorage).