Chapter 1 of 4
What Makes a Custom Hook
The naming rule, what gets shared and what does not.
A custom hook is a function whose name begins with use and which calls other hooks. That is all. There is no special API and no registration - it is a plain function that happens to follow the rules of hooks.
import { useState, useEffect } from "react";
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() { setWidth(window.innerWidth); }
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return width;
}
function Layout() {
const width = useWindowWidth();
return width < 768 ? <MobileNav /> : <DesktopNav />;
}Why the name has to start with use
The prefix is how both React's linter and other developers know the function may call hooks, and therefore that the rules of hooks apply to it. Without the prefix the lint rules cannot check your calls.
Hooks share logic, not state
Every component that calls a hook gets its own independent state. Two components using useWindowWidth each have their own width and their own listener.
function A() { const width = useWindowWidth(); } // its own state
function B() { const width = useWindowWidth(); } // a separate stateThe rules still apply
- Call hooks at the top level - never inside a condition, loop or nested function.
- Call them only from components or from other custom hooks.
- The order of hook calls must be identical on every render.