Custom Hooks: Extracting Reusable Logic
Move stateful logic into custom use* functions to share behaviour across components without duplicating code or lifting state.
What Are Custom Hooks?
A custom hook is a JavaScript function whose name starts with use and that calls other hooks internally. Custom hooks let you extract stateful logic so multiple components can share it without copy-pasting.
Extracting Logic into a Custom Hook
Identify logic that's duplicated across components (fetch + loading + error, window size, local storage) and move it into a custom hook.
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;
}
// Usage:
const width = useWindowWidth();
const isMobile = width < 768;All lessons in this course
- useContext for Global State
- useReducer for Complex State
- useMemo and useCallback for Performance
- Custom Hooks: Extracting Reusable Logic