fix useWindowSize (again)

This commit is contained in:
Asad Umar 2022-02-04 23:37:46 +05:00 committed by Thomas Zarebczan
parent e45ef63d41
commit df320a2375

View file

@ -1,16 +1,20 @@
// Widths are taken from "ui/scss/init/vars.scss"
import React from 'react';
import React, { useRef } from 'react';
export function useWindowSize(fn) {
const isWindowClient = typeof window === 'object';
const initialState = fn ? fn(window.innerWidth) : window.innerWidth;
const [windowSize, setWindowSize] = React.useState(isWindowClient ? initialState : undefined);
const prev = useRef();
React.useEffect(() => {
function setSize() {
if (fn) {
const curr = fn(window.innerWidth);
if (windowSize !== curr) setWindowSize(curr);
if (prev !== curr) {
setWindowSize(curr);
prev.current = curr;
}
} else setWindowSize(window.innerWidth);
}
@ -21,7 +25,7 @@ export function useWindowSize(fn) {
return () => window.removeEventListener('resize', setSize);
}
}, [isWindowClient, setWindowSize]);
}, [fn, isWindowClient, setWindowSize, windowSize]);
return windowSize;
}