orcs-design-system
Version:
TeamForm's Design System, aka: ORCS
50 lines (49 loc) • 1.7 kB
JavaScript
import { useState, useEffect } from "react";
import { BREAKPOINTS, RESIZE_CONFIG } from "../constants/sideNav";
/**
* Custom hook to handle responsive behavior for the SideNavV2 component
*
* Listens to window resize with debouncing and exposes window width and
* a small-screen flag (window width <= breakpoint).
*
* @param {number} [breakpoint=BREAKPOINTS.SMALL_SCREEN] - Breakpoint (px) for small screen detection (default 900)
* @returns {Object} Object containing windowWidth and isSmallScreen
*/
const useResponsive = function () {
let breakpoint = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : BREAKPOINTS.SMALL_SCREEN;
const [windowWidth, setWindowWidth] = useState(() => {
// Safely get initial window width, handling SSR
if (typeof window !== "undefined") {
return window.innerWidth;
}
return breakpoint + 1; // Default to large screen for SSR
});
const isSmallScreen = windowWidth <= breakpoint;
useEffect(() => {
// Only run on client side
if (typeof window === "undefined") {
return;
}
let timeoutId;
const handleResize = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
const newWidth = window.innerWidth;
// Only update if width actually changed
if (newWidth !== windowWidth) {
setWindowWidth(newWidth);
}
}, RESIZE_CONFIG.RESIZE_DEBOUNCE_MS);
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
clearTimeout(timeoutId);
};
}, [windowWidth]);
return {
windowWidth,
isSmallScreen
};
};
export default useResponsive;