Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. // @flow
  2. import { useState, useLayoutEffect } from 'react';
  3.  
  4. /**
  5. * This hook allows you to detect window size
  6. * @param handler Function
  7. * @return Object window size (number width, number height)
  8. * */
  9. export function useWindowSize(handler: Function): { width: number, height: number } {
  10. const isClient = typeof window === 'object';
  11. // delay between calls
  12. const delay = 200;
  13.  
  14. const getSize = (): { width: number, height: number } => {
  15. return {
  16. width: isClient ? window.innerWidth : 0,
  17. height: isClient ? window.innerHeight : 0,
  18. };
  19. };
  20.  
  21. const [windowSize, setWindowSize] = useState(getSize());
  22. const [throttled, setThrottled] = useState(false);
  23.  
  24. const handleResize = (): void => {
  25. if (!throttled) {
  26. // actual callback action
  27. handler(getSize());
  28. setWindowSize(getSize());
  29.  
  30. // we're throttled!
  31. setThrottled(true);
  32.  
  33. // set a timeout to un-throttle
  34. setTimeout(() => {
  35. setThrottled(false);
  36. }, delay);
  37. }
  38. };
  39.  
  40. useLayoutEffect((): Object => {
  41. if (!isClient) {
  42. return undefined;
  43. }
  44. handler(getSize());
  45. setWindowSize(getSize());
  46.  
  47. window.addEventListener('resize', handleResize);
  48. return () => window.removeEventListener('resize', handleResize);
  49. }, [throttled]);
  50.  
  51. return windowSize;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement