Skip to content

Commit

Permalink
refactor(utils): remove use of lodash/throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
gcornut committed Jan 31, 2025
1 parent b0fe136 commit 96daa21
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions packages/lumx-react/src/hooks/useSizeOnWindowResize.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from 'react';

import throttle from 'lodash/throttle';
import { RectSize } from '@lumx/react/utils/type';
import type { RectSize } from '@lumx/react/utils/type';

/**
* Observe element size (only works if it's size depends on the window size).
Expand All @@ -13,14 +12,19 @@ import { RectSize } from '@lumx/react/utils/type';
*/
export function useSizeOnWindowResize(elementRef: React.RefObject<HTMLElement>): [RectSize | null, () => void] {
const [size, setSize] = React.useState<null | RectSize>(null);
const updateSize = React.useMemo(
() =>
throttle(() => {
const newSize = elementRef.current?.getBoundingClientRect();
if (newSize) setSize(newSize);
}, 10),
[elementRef],
);
const updateSize = React.useMemo(() => {
let prevTimeout: ReturnType<typeof setTimeout> | undefined;
function update() {
const newSize = elementRef.current?.getBoundingClientRect();
if (newSize) setSize(newSize);
prevTimeout = undefined;
}
return () => {
if (!prevTimeout) {
prevTimeout = setTimeout(update, 10);
}
};
}, [elementRef]);
React.useEffect(() => {
updateSize();
window.addEventListener('resize', updateSize);
Expand Down

0 comments on commit 96daa21

Please sign in to comment.