Skip to content

Commit

Permalink
add useBreakpoints hook
Browse files Browse the repository at this point in the history
  • Loading branch information
alissacrane-cb committed Aug 13, 2024
1 parent 7d03bf3 commit 111b634
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/useBreakpoints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useState, useEffect } from "react";

// tailwind breakpoints
const breakpoints = {
sm: "(max-width: 640px)",
md: "(min-width: 641px) and (max-width: 768px)",
lg: "(min-width: 769px) and (max-width: 1023px)",
xl: "(min-width: 1024px) and (max-width: 1279px)",
"2xl": "(min-width: 1280px)",
};

export function useBreakpoints() {
const [currentBreakpoint, setCurrentBreakpoint] = useState<string>("md");

// handles SSR case where window would be undefined,
// once component mounts on client, hook sets correct breakpoint
useEffect(() => {
// get the current breakpoint based on media queries
const getCurrentBreakpoint = () => {
const entries = Object.entries(breakpoints) as [string, string][];
for (const [key, query] of entries) {
if (window.matchMedia(query).matches) {
return key;
}
}
return 'md';
};

// set initial breakpoint
setCurrentBreakpoint(getCurrentBreakpoint());

// listen changes in the window size
const handleResize = () => {
setCurrentBreakpoint(getCurrentBreakpoint());
};

window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);

return currentBreakpoint;
}

export default useBreakpoints;

0 comments on commit 111b634

Please sign in to comment.