Skip to content

Instantly share code, notes, and snippets.

@LukaGiorgadze
Last active October 3, 2019 10:05
Show Gist options
  • Save LukaGiorgadze/f8f2c2446860234c44ba45d074b9afce to your computer and use it in GitHub Desktop.
Save LukaGiorgadze/f8f2c2446860234c44ba45d074b9afce to your computer and use it in GitHub Desktop.
This hook allows you to detect window size and resize.
// @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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment