From d966751c223e297fc809e54061b8b75a7ad9337f Mon Sep 17 00:00:00 2001 From: vgcman16 <155417613+vgcman16@users.noreply.github.com> Date: Thu, 5 Jun 2025 21:29:52 -0500 Subject: [PATCH] fix: handle SSR in useViewport --- app/lib/hooks/useViewport.ts | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/app/lib/hooks/useViewport.ts b/app/lib/hooks/useViewport.ts index c23c7264..fa8268ae 100644 --- a/app/lib/hooks/useViewport.ts +++ b/app/lib/hooks/useViewport.ts @@ -1,10 +1,28 @@ import { useState, useEffect } from 'react'; -const useViewport = (threshold = 1024) => { - const [isSmallViewport, setIsSmallViewport] = useState(window.innerWidth < threshold); +/** + * Determine the current viewport width in both browser and server contexts. + * When `window` is not available (e.g. during SSR), a fallback width is used. + */ +const getWidth = (fallback: number): number => + typeof window !== 'undefined' ? window.innerWidth : fallback; + +/** + * Returns `true` if the viewport width is less than the provided threshold. + * A `fallbackWidth` can be supplied for server environments where `window` + * is undefined. + */ +const useViewport = (threshold = 1024, fallbackWidth = 1024) => { + const [isSmallViewport, setIsSmallViewport] = useState( + getWidth(fallbackWidth) < threshold, + ); useEffect(() => { - const handleResize = () => setIsSmallViewport(window.innerWidth < threshold); + if (typeof window === 'undefined') return; + + const handleResize = () => + setIsSmallViewport(window.innerWidth < threshold); + window.addEventListener('resize', handleResize); return () => {