From e4b6a1a9db2f4c7ab57584715adfe85c7d50b014 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 9 Sep 2021 22:12:11 +0300 Subject: [PATCH] Add useWindowSize --- snippets/useWindowSize.md | 49 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 snippets/useWindowSize.md diff --git a/snippets/useWindowSize.md b/snippets/useWindowSize.md new file mode 100644 index 000000000..c30c2765b --- /dev/null +++ b/snippets/useWindowSize.md @@ -0,0 +1,49 @@ +--- +title: useWindowSize +tags: hooks,state,effect,intermediate +firstSeen: 2021-10-18T05:00:00-04:00 +--- + +Tracks the dimensions of the browser window. + +- Use the `useState()` hook to initialize a state variable that will hold the window's dimensions. Initialize with both values set to `undefined` to avoid mismatch between server and client renders. +- Create a function that uses `Window.innerWidth` and `Window.innerHeight` to update the state variable. +- Use the `useEffect()` hook to set an appropriate listener for the `'resize'` event on mount and clean it up when unmounting. + +```jsx +const useWindowSize = () => { + const [windowSize, setWindowSize] = React.useState({ + width: undefined, + height: undefined, + }); + + React.useEffect(() => { + const handleResize = () => + setWindowSize({ width: window.innerWidth, height: window.innerHeight }); + + window.addEventListener('resize', handleResize); + + handleResize(); + + return () => { + window.removeEventListener('resize', handleResize); + }; + }, []); + + return windowSize; +}; +``` + +```jsx +const MyApp = () => { + const { width, height } = useWindowSize(); + + return ( +

+ Window size: ({width} x {height}) +

+ ); +}; + +ReactDOM.render(, document.getElementById('root')); +```