Skip to content

Commit

Permalink
feat: Add useOnResize hook (#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
rossbulat authored Nov 2, 2024
1 parent e8e4200 commit 0e989cb
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
2 changes: 1 addition & 1 deletion library/hooks/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@w3ux/hooks-source",
"license": "GPL-3.0-only",
"version": "1.2.0",
"version": "1.2.1-beta.0",
"type": "module",
"scripts": {
"clear": "rm -rf node_modules dist tsconfig.tsbuildinfo",
Expand Down
1 change: 1 addition & 0 deletions library/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
SPDX-License-Identifier: GPL-3.0-only */

export * from "./useEffectIgnoreInitial";
export * from "./useOnResize";
export * from "./useOutsideAlerter";
export * from "./useSize";
40 changes: 40 additions & 0 deletions library/hooks/src/useOnResize.tsx
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]);
};

0 comments on commit 0e989cb

Please sign in to comment.