Part 07 / Topic 2 of 6
Extracting a custom hook
examples/02_use_window_width.jsx moves the exact same logic into one function, useWindowWidth, and both components call it instead:
// examples/02_use_window_width.jsx
export 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;
}
export function CartBadge() {
const width = useWindowWidth();
return <p>Cart badge layout width: {width}px</p>;
}
Nothing here is new syntax - useWindowWidth is a plain JavaScript function that happens to call useState and useEffect inside itself. The use prefix is the one piece of convention that matters: it is how React's own tooling (and oxlint's react/rules-of-hooks rule, Section 4) recognizes which plain functions are allowed to call other hooks. Resizing the window after rendering both components really still updates both (examples/02_use_window_width.test.jsx) - the only thing that changed is that the resize-tracking code now exists exactly once.
Done here? The practice set for Part 7 — including the solutions — is on the part page.