fix useWindowSize (again)
This commit is contained in:
parent
e45ef63d41
commit
df320a2375
1 changed files with 7 additions and 3 deletions
|
@ -1,16 +1,20 @@
|
||||||
// Widths are taken from "ui/scss/init/vars.scss"
|
// Widths are taken from "ui/scss/init/vars.scss"
|
||||||
import React from 'react';
|
import React, { useRef } from 'react';
|
||||||
|
|
||||||
export function useWindowSize(fn) {
|
export function useWindowSize(fn) {
|
||||||
const isWindowClient = typeof window === 'object';
|
const isWindowClient = typeof window === 'object';
|
||||||
const initialState = fn ? fn(window.innerWidth) : window.innerWidth;
|
const initialState = fn ? fn(window.innerWidth) : window.innerWidth;
|
||||||
const [windowSize, setWindowSize] = React.useState(isWindowClient ? initialState : undefined);
|
const [windowSize, setWindowSize] = React.useState(isWindowClient ? initialState : undefined);
|
||||||
|
const prev = useRef();
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
function setSize() {
|
function setSize() {
|
||||||
if (fn) {
|
if (fn) {
|
||||||
const curr = fn(window.innerWidth);
|
const curr = fn(window.innerWidth);
|
||||||
if (windowSize !== curr) setWindowSize(curr);
|
if (prev !== curr) {
|
||||||
|
setWindowSize(curr);
|
||||||
|
prev.current = curr;
|
||||||
|
}
|
||||||
} else setWindowSize(window.innerWidth);
|
} else setWindowSize(window.innerWidth);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -21,7 +25,7 @@ export function useWindowSize(fn) {
|
||||||
|
|
||||||
return () => window.removeEventListener('resize', setSize);
|
return () => window.removeEventListener('resize', setSize);
|
||||||
}
|
}
|
||||||
}, [isWindowClient, setWindowSize]);
|
}, [fn, isWindowClient, setWindowSize, windowSize]);
|
||||||
|
|
||||||
return windowSize;
|
return windowSize;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue