@ozen-ui/kit
Version:
React component library
40 lines (39 loc) • 1.54 kB
JavaScript
import { useEffect } from 'react';
import { useOzenSSR } from '../../components/OzenProvider';
import { calculateBreakpoints } from '../../utils/breakpoint';
import { useEventListener } from '../useEventListener';
import { useIsomorphicEffect } from '../useIsomorphicEffect';
import { useStoredValue } from '../useStoredValue';
import { useTheme } from '../useTheme';
export function useBreakpointsObserver(onChange) {
var ssr = useOzenSSR();
var theme = useTheme();
var breakpointToken = theme.tokens.breakpoint;
var matches = useStoredValue(function () {
if (ssr.config.isEnabled) {
return calculateBreakpoints(breakpointToken, ssr.config.serverWidth);
}
return calculateBreakpoints(breakpointToken, window.innerWidth);
});
var recalculateMatches = function (width) {
var newMatches = calculateBreakpoints(breakpointToken, width);
var hasChanges = newMatches.currentBreakpoint !== matches.current.currentBreakpoint;
if (hasChanges) {
matches.current = newMatches;
onChange === null || onChange === void 0 ? void 0 : onChange(newMatches, width);
}
};
useEffect(function () {
recalculateMatches(window.innerWidth);
}, [theme]);
useEventListener({
eventName: 'resize',
handler: function () {
recalculateMatches(window.innerWidth);
},
});
useIsomorphicEffect(function () {
recalculateMatches(window.innerWidth);
}, []);
return matches;
}