fix useScreensize

This commit is contained in:
Asad Umar 2022-01-31 17:34:44 +05:00 committed by Thomas Zarebczan
parent e0f01a58d2
commit 00c9410253
2 changed files with 18 additions and 12 deletions

View file

@ -2,13 +2,17 @@ import { useEffect } from 'react';
import debounce from 'util/debounce';
export function useOnResize(cb) {
const isWindowClient = typeof window === 'object';
useEffect(() => {
const handleResize = debounce(cb, 100);
if (isWindowClient) {
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
}
}, [isWindowClient]);
}

View file

@ -1,18 +1,23 @@
// Widths are taken from "ui/scss/init/vars.scss"
import React from 'react';
function useWindowSize() {
export function useWindowSize(fn) {
const isWindowClient = typeof window === 'object';
const [windowSize, setWindowSize] = React.useState(isWindowClient ? window.innerWidth : undefined);
React.useEffect(() => {
function setSize() {
setWindowSize(window.innerWidth);
if (fn) {
const curr = fn(window.innerWidth);
if (windowSize !== curr) setWindowSize(curr);
} else setWindowSize(window.innerWidth);
}
if (isWindowClient) {
window.addEventListener('resize', setSize);
setSize();
return () => window.removeEventListener('resize', setSize);
}
}, [isWindowClient, setWindowSize]);
@ -21,16 +26,13 @@ function useWindowSize() {
}
export function useIsMobile() {
const windowSize = useWindowSize();
return windowSize < 901;
return useWindowSize((windowSize) => windowSize < 901);
}
export function useIsMediumScreen() {
const windowSize = useWindowSize();
return windowSize < 1151;
return useWindowSize((windowSize) => windowSize < 1151);
}
export function useIsLargeScreen() {
const windowSize = useWindowSize();
return windowSize > 1600;
return useWindowSize((windowSize) => windowSize > 1600);
}