Skip to content
ClapelloNotes by Barath
ReactCh 09 · 2/6
Core5 min readUpdated

React / 47

Custom hooks

TL;DR

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

hooks/useOnlineStatus.js
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

RuleWhy
Name it use + a capital letter: useOnlineStatus, not onlineStatus or useonlineThe 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 functionsReact 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 hooksHooks 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)]}
called by

<LikeButton />

its own n = 3
called by

<CartBadge />

its own n = 0
A custom hook is a recipe, not a shared pot. Each component that calls it gets its own fresh state.

One hook, two components

Try it

<LikeButton />

calls useCounter()

0

<CartBadge />

calls useCounter()

0

Click one card a few times. The other stays at 0: the hook shares the logic, never the state.

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:

hooks/useFetch.js
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 url changes 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 loading state to forget to reset.

Hooks can call hooks, so the useMenu from the previous topic is two lines:

hooks/useMenu.js
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.