Skip to content

Instantly share code, notes, and snippets.

@p32929
Created August 30, 2024 11:40
Show Gist options
  • Save p32929/e8abdbbabce1b499400b56f59b09d815 to your computer and use it in GitHub Desktop.
Save p32929/e8abdbbabce1b499400b56f59b09d815 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
const breakpoints = {
// sm: 640,
// md: 768,
lg: 1024,
// xl: 1280,
};
const getBreakpoint = (width) => {
// if (width >= breakpoints.xl) return 'xl';
if (width >= breakpoints.lg) return 'lg';
// if (width >= breakpoints.md) return 'md';
// if (width >= breakpoints.sm) return 'sm';
return 'default';
};
const useBreakpoint = () => {
const [breakpoint, setBreakpoint] = useState(() => {
// Check if window is defined to avoid server-side rendering issues
if (typeof window !== 'undefined') {
return getBreakpoint(window.innerWidth);
}
return 'default';
});
useEffect(() => {
// Only run the effect on the client
if (typeof window !== 'undefined') {
const handleResize = () => {
setBreakpoint(getBreakpoint(window.innerWidth));
};
window.addEventListener('resize', handleResize);
// Initial setting of breakpoint
handleResize();
return () => {
window.removeEventListener('resize', handleResize);
};
}
}, []);
return breakpoint;
};
export default useBreakpoint;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment