Custom Hook
In one line
A custom Hook is a user-defined function starting with 'use' that extracts and reuses stateful logic across components.
In simple words
A custom Hook is a JavaScript function whose name starts with use and that can call other Hooks inside it. It lets you extract component logic into a reusable function, just like you extract JSX into a component.
For example, a useWindowWidth() Hook could encapsulate the logic for tracking the browser window width. Any component can call const width = useWindowWidth() and get the current width, with all the event listener setup and cleanup hidden inside the Hook.
Custom Hooks are the primary way to share stateful logic in modern React. They replaced higher-order components and render props patterns. The naming convention (use...) is required so React's linter can enforce the Rules of Hooks.
Example
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handler = () => setWidth(window.innerWidth);
window.addEventListener("resize", handler);
return () => window.removeEventListener("resize", handler);
}, []);
return width;
}
// Use it anywhere
function MyComponent() {
const width = useWindowWidth();
return <p>Window is {width}px wide</p>;
}useWindowWidth encapsulates the resize listener and state. Any component can call it to get the current window width.
Related terms
Related Resources
Related Lessons
- Custom Hooks
Learn to build and reuse custom Hooks.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.