Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/public-frogs-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@wpmudev/sui-css": patch
"@wpmudev/sui-hooks": patch
---

useResponsive hook resize issue
19 changes: 18 additions & 1 deletion packages/hooks/src/use-responsive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,20 @@ const useResponsive = (config: ConfigType = {}) => {
const [device, setDevice] = useState(() => getDevice(defaultBreakpoints))

useEffect(() => {
const handleResize = () => setDevice(getDevice(defaultBreakpoints))
let timeoutId: ReturnType<typeof setTimeout> | 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) => {
Expand All @@ -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),
)
Expand Down