React ยท Chapter 19 of 42

Custom Hooks

A custom hook is a JavaScript function whose name starts with `use` and that can call other hooks. Custom hooks let you extract and reuse stateful logic across components.

They don't share state between components โ€” each call gets its own independent state โ€” but they let you share the logic itself.

Creating a custom hook

Extract repeated logic (like fetching data or tracking window size) into a function named `useSomething` that uses built-in hooks internally.

Why use them?

Custom hooks keep components clean by moving reusable logic out, and make that logic easy to test in isolation.

Example 1 (jsx)
import { useState, useEffect } from "react";

function useOnlineStatus() {
  const [online, setOnline] = useState(navigator.onLine);
  useEffect(() => {
    const update = () => setOnline(navigator.onLine);
    window.addEventListener("online", update);
    window.addEventListener("offline", update);
    return () => {
      window.removeEventListener("online", update);
      window.removeEventListener("offline", update);
    };
  }, []);
  return online;
}

function StatusBadge() {
  const online = useOnlineStatus();
  return <span>{online ? "Online" : "Offline"}</span>;
}
Output
Online (updates automatically)

useOnlineStatus encapsulates reusable connectivity-tracking logic.

Key points

  • Custom hooks are functions starting with 'use' that call other hooks.
  • They let you reuse stateful logic across multiple components.
  • Each component using a custom hook gets independent state.
  • Custom hooks improve testability and readability.
๐Ÿ’ก Note: Custom hooks are a naming convention plus a composition pattern โ€” there's no special React API for them.

๐Ÿ“ Quick Quiz

1. What must a custom hook's name start with?

2. Do components sharing a custom hook share the same state?

3. What is the main benefit of custom hooks?