SHARE
TWEET

Untitled

a guest Mar 21st, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useState, useEffect } from 'react';
  2.  
  3. /*
  4.   Hook to listen for and return the current
  5.   window inner width and innher height
  6.  
  7.   ## Usage:
  8.   ```
  9.   const [width, height] = useWindowSize();
  10.   width >= 991 ? 'desktop' : 'mobile'
  11.   ```
  12. */
  13.  
  14. export default function useWindowSize() {
  15.   const [width, updateWidth] = useState(window.innerWidth);
  16.   const [height, updateHeight] = useState(window.innerHeight);
  17.  
  18.   const handleResize = () => {
  19.     updateWidth(window.innerWidth);
  20.     updateHeight(window.innerHeight);
  21.   };
  22.  
  23.   useEffect(() => {
  24.     window.addEventListener('resize', handleResize);
  25.     return () => window.removeEventListener('resize', handleResize);
  26.   }, []);
  27.  
  28.   return [width, height];
  29. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top