How to build a custom React hook
· Category: React
Short answer
A custom hook is a JavaScript function whose name starts with use and that may call other hooks. It lets you extract and reuse stateful logic across components.
Steps
- Identify duplicated logic involving hooks in multiple components.
- Extract it into a function named
useSomething. - Return the values and callbacks the component needs.
- Call it like any standard hook inside a component.
Example
import { useState, useEffect } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
function MyComponent() {
const width = useWindowWidth();
return <p>Window width: {width}px</p>;
}
Tips
- Keep custom hooks focused on a single concern.
- Document the return shape and assumptions (e.g., whether the hook expects a mounted component).
- Avoid calling hooks conditionally inside custom hooks; follow the Rules of Hooks.