@modern-kit/react
Version:
33 lines (30 loc) • 966 B
JavaScript
import { useSyncExternalStore } from 'react';
import { debounce, isNumber } from '@modern-kit/utils';
const DEFAULT_SIZE = { width: 0, height: 0 };
const subscribe = (onStoreChange, wait) => {
const debouncedCallback = debounce(onStoreChange, wait ?? 0);
const handleStoreChange = isNumber(wait) ? debouncedCallback : onStoreChange;
window.addEventListener("resize", handleStoreChange);
return () => {
window.removeEventListener("resize", handleStoreChange);
};
};
const getSnapshot = () => {
return JSON.stringify({
width: window.innerWidth,
height: window.innerHeight
});
};
const getServerSnapshot = () => {
return JSON.stringify(DEFAULT_SIZE);
};
function useWindowSize(debounceWait) {
const windowSize = useSyncExternalStore(
(onStoreChange) => subscribe(onStoreChange, debounceWait),
getSnapshot,
getServerSnapshot
);
return JSON.parse(windowSize);
}
export { useWindowSize };
//# sourceMappingURL=index.mjs.map