Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // @flow
- import { useState, useLayoutEffect } from 'react';
- /**
- * This hook allows you to detect window size
- * @param handler Function
- * @return Object window size (number width, number height)
- * */
- export function useWindowSize(handler: Function): { width: number, height: number } {
- const isClient = typeof window === 'object';
- // delay between calls
- const delay = 200;
- const getSize = (): { width: number, height: number } => {
- return {
- width: isClient ? window.innerWidth : 0,
- height: isClient ? window.innerHeight : 0,
- };
- };
- const [windowSize, setWindowSize] = useState(getSize());
- const [throttled, setThrottled] = useState(false);
- const handleResize = (): void => {
- if (!throttled) {
- // actual callback action
- handler(getSize());
- setWindowSize(getSize());
- // we're throttled!
- setThrottled(true);
- // set a timeout to un-throttle
- setTimeout(() => {
- setThrottled(false);
- }, delay);
- }
- };
- useLayoutEffect((): Object => {
- if (!isClient) {
- return undefined;
- }
- handler(getSize());
- setWindowSize(getSize());
- window.addEventListener('resize', handleResize);
- return () => window.removeEventListener('resize', handleResize);
- }, [throttled]);
- return windowSize;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement