diff --git a/.changeset/public-frogs-hunt.md b/.changeset/public-frogs-hunt.md new file mode 100644 index 000000000..cf634d2f6 --- /dev/null +++ b/.changeset/public-frogs-hunt.md @@ -0,0 +1,6 @@ +--- +"@wpmudev/sui-css": patch +"@wpmudev/sui-hooks": patch +--- + +useResponsive hook resize issue diff --git a/packages/hooks/src/use-responsive.ts b/packages/hooks/src/use-responsive.ts index 002a40979..cea189de4 100644 --- a/packages/hooks/src/use-responsive.ts +++ b/packages/hooks/src/use-responsive.ts @@ -62,7 +62,20 @@ const useResponsive = (config: ConfigType = {}) => { const [device, setDevice] = useState(() => getDevice(defaultBreakpoints)) useEffect(() => { - const handleResize = () => setDevice(getDevice(defaultBreakpoints)) + let timeoutId: ReturnType | null = null + + const handleResize = () => { + if (timeoutId) { + clearTimeout(timeoutId) + } + timeoutId = setTimeout(() => { + const newDevice = getDevice(defaultBreakpoints) + setDevice(newDevice) + }, 100) + } + + // Add window resize listener as fallback + window.addEventListener("resize", handleResize) // initialize matchMedia for each device and listen for changes const mediaQueries = Object.values(defaultBreakpoints).map((value) => { @@ -73,6 +86,10 @@ const useResponsive = (config: ConfigType = {}) => { // cleanup event listeners on unmount return () => { + if (timeoutId) { + clearTimeout(timeoutId) + } + window.removeEventListener("resize", handleResize) mediaQueries.forEach((mediaList) => mediaList.removeEventListener("change", handleResize), )