Part 07 / Topic 1 of 6
The problem: the same logic, typed twice
examples/01_window_width_duplicated.jsx has two components that both need the current window width - each with its own useState, its own resize listener, its own cleanup:
// examples/01_window_width_duplicated.jsx
export function CartBadge() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return <p>Cart badge layout width: {width}px</p>;
}
// NavWidthReadout repeats this exact block, word for word
Both components really do work (examples/01_window_width_duplicated.test.jsx resizes the window and checks both update), but the resize-tracking logic itself now exists in two places that have to be kept identical by hand. A third component that needs the same thing means a third copy. This is the felt problem a custom hook responds to - not an abstract rule about code reuse, but two real blocks of identical code sitting in the same file.
Done here? The practice set for Part 7 — including the solutions — is on the part page.