Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement