Merge pull request #37 from vgcman16/codex/update-useviewport-for-ssr-compatibility

Fix SSR compatibility in useViewport
This commit is contained in:
vgcman16 2025-06-05 21:30:12 -05:00 committed by GitHub
commit a87477f504
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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 () => {