fix: handle SSR in useViewport

This commit is contained in:
vgcman16 2025-06-05 21:29:52 -05:00
parent 1d66831395
commit d966751c22

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