Skip to content

Commit 86c100c

Browse files
committed
useBreakpoints Hook
1 parent 0a660e1 commit 86c100c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import useBreakpoints from "./useBreakpoints";
2+
3+
export default function BreakpointsComponent() {
4+
const { isMobile, isTablet } = useBreakpoints();
5+
6+
return (
7+
<>
8+
{isMobile && <div>Mobile</div>}
9+
{isTablet && <div>Tablet</div>}
10+
</>
11+
);
12+
}
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { useState, useEffect } from "react";
2+
3+
const useBreakpoints = () => {
4+
const [currentBreakpoint, setCurrentBreakpoint] = useState("");
5+
6+
useEffect(() => {
7+
const handleResize = () => {
8+
const mobileMatch = window.matchMedia("(min-width: 320px)");
9+
const tabletMatch = window.matchMedia("(min-width: 768px)");
10+
const desktopMatch = window.matchMedia("(min-width: 1024px)");
11+
12+
if (desktopMatch.matches) {
13+
setCurrentBreakpoint("desktop");
14+
} else if (tabletMatch.matches) {
15+
setCurrentBreakpoint("tablet");
16+
} else if (mobileMatch.matches) {
17+
setCurrentBreakpoint("mobile");
18+
}
19+
};
20+
21+
handleResize(); // Initial check
22+
window.addEventListener("resize", handleResize);
23+
return () => window.removeEventListener("resize", handleResize);
24+
}, []);
25+
26+
const isMobile = currentBreakpoint === "mobile";
27+
const isTablet = currentBreakpoint === "tablet";
28+
const isDesktop = currentBreakpoint === "desktop";
29+
30+
return {
31+
isMobile,
32+
isTablet,
33+
isDesktop,
34+
};
35+
};
36+
37+
export default useBreakpoints;

0 commit comments

Comments
 (0)