Track window width with a hook

React · React · advanced · greenfield

Adds a `useWindowWidth` hook for responsive layouts. Subscribes to the window resize event, returns the current width, and removes the listener on unmount.

Requirements

Files touched

--- src/hooks/useWindowWidth.js
+function useWindowWidth() {
+  const [width, setWidth] = useState(window.innerWidth);
+  useEffect(() => {
+    const onResize = () => setWidth(window.innerWidth);
+    window.addEventListener('resize', onResize);
+    return () => window.removeEventListener('resize', onResize);
+  }, []);
+  return width;
+}
+
+export default useWindowWidth;

Review this PR

React practice