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
- Return the current window width from a hook.
- Keep it in sync when the window is resized.
- Don't leak event listeners.
Files touched
- src/hooks/useWindowWidth.js
--- 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;