Rules of Hooks

Hooks such as useState, useEffect, and useMemo must be called at the top level of React function components or custom hooks. Do not call hooks inside loops, conditions, nested functions, or arbitrary utility functions.

React relies on a consistent hook call order to associate hook state with a component render. Conditional hook calls change that order and break the association.

Custom hooks are functions whose names begin with use and that can call other hooks. They package reusable stateful behavior without sharing component state implicitly.

A custom hook
function useOnlineStatus() {
  const [online, setOnline] = useState(navigator.onLine);

  useEffect(() => {
    const onOnline = () => setOnline(true);
    const onOffline = () => setOnline(false);
    window.addEventListener("online", onOnline);
    window.addEventListener("offline", onOffline);
    return () => {
      window.removeEventListener("online", onOnline);
      window.removeEventListener("offline", onOffline);
    };
  }, []);

  return online;
}
💡 The hook owns the subscription lifecycle and exposes a small reusable API.
Key Takeaways
  • Hooks require stable call order.
  • Custom hooks share behavior, not state instances.
  • A custom hook should have a focused contract.