Skip to content
This repository was archived by the owner on Jul 20, 2025. It is now read-only.

Commit 5e49859

Browse files
feat:update throttle
1 parent 12e6522 commit 5e49859

File tree

3 files changed

+23
-13
lines changed

3 files changed

+23
-13
lines changed

package-lock.json

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,10 @@
9696
"dependencies": {
9797
"@hookform/resolvers": "^3.9.1",
9898
"@popperjs/core": "^2.11.8",
99+
"decimal.js-light": "^2.5.1",
100+
"lodash": "^4.17.21",
99101
"react-hook-form": "^7.54.0",
100102
"react-popper": "^2.3.0",
101-
"decimal.js-light": "^2.5.1",
102103
"tw-colors": "^3.3.2"
103104
}
104-
}
105+
}

src/hooks/useIsMobile.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
import { useState, useEffect } from "react";
1+
import { useState, useEffect, useCallback, useRef } from "react";
2+
import { throttle } from "lodash";
23

34
/**
45
* Hook to detect if the viewport is in mobile size
56
* @param breakpoint - The breakpoint in pixels (default: 768)
7+
* @param throttleMs - The throttle delay in milliseconds (default: 100)
68
* @returns boolean indicating if viewport is mobile size
79
*/
8-
export function useIsMobile(breakpoint: number = 768): boolean {
10+
export function useIsMobile(breakpoint: number = 768, throttleMs: number = 100): boolean {
911
const [isMobile, setIsMobile] = useState(() => {
1012
// Initial state based on current window width
1113
if (typeof window !== "undefined") {
@@ -14,17 +16,23 @@ export function useIsMobile(breakpoint: number = 768): boolean {
1416
return false;
1517
});
1618

17-
useEffect(() => {
18-
const checkMobile = () => {
19-
setIsMobile(window.innerWidth < breakpoint);
20-
};
19+
const throttledCheckMobile = useRef<(() => void) | null>(null);
2120

22-
checkMobile();
21+
const checkMobile = useCallback(() => {
22+
setIsMobile(window.innerWidth < breakpoint);
23+
}, [breakpoint]);
2324

24-
window.addEventListener("resize", checkMobile);
25+
useEffect(() => {
26+
throttledCheckMobile.current = throttle(checkMobile, throttleMs);
27+
checkMobile();
28+
window.addEventListener("resize", throttledCheckMobile.current);
2529

26-
return () => window.removeEventListener("resize", checkMobile);
27-
}, [breakpoint]);
30+
return () => {
31+
if (throttledCheckMobile.current) {
32+
window.removeEventListener("resize", throttledCheckMobile.current);
33+
}
34+
};
35+
}, [checkMobile, throttleMs]);
2836

2937
return isMobile;
3038
}

0 commit comments

Comments
 (0)