-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { MutableRefObject, useEffect, useRef } from "react"; | ||
|
||
interface UseOnResizeOptions { | ||
outerElement?: MutableRefObject<HTMLElement | null | undefined>; | ||
throttle?: number; | ||
} | ||
|
||
// Hook to execute a callback function on window resize, with optional throttling. | ||
export const useOnResize = ( | ||
callback: () => void, | ||
options: UseOnResizeOptions = {} | ||
) => { | ||
const { outerElement, throttle: throttleDuration = 100 } = options; | ||
const lastExecutedRef = useRef<number>(0); | ||
|
||
// Throttled resize handler | ||
const handleResize = () => { | ||
const now = Date.now(); | ||
if (now - lastExecutedRef.current < throttleDuration) { | ||
return; | ||
} | ||
|
||
lastExecutedRef.current = now; | ||
callback(); | ||
}; | ||
|
||
useEffect(() => { | ||
// Determine the target for the resize event listener. | ||
// If `outerElement` is provided, listen to its resize events; otherwise, listen to the window's. | ||
const listenFor = outerElement?.current || window; | ||
|
||
// Add event listener for resize on mount. | ||
listenFor.addEventListener("resize", handleResize); | ||
|
||
// Clean up event listener on unmount. | ||
return () => { | ||
listenFor.removeEventListener("resize", handleResize); | ||
}; | ||
}, [throttleDuration, callback]); | ||
}; |