Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 22 additions & 18 deletions src/components/PaginatedTable/useScrollBasedChunks.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import React from 'react';

import {throttle} from 'lodash';

import {calculateElementOffsetTop} from './utils';
import {calculateElementOffsetTop, rafThrottle} from './utils';

interface UseScrollBasedChunksProps {
parentRef: React.RefObject<HTMLElement>;
Expand All @@ -14,7 +12,6 @@ interface UseScrollBasedChunksProps {
}

const DEFAULT_OVERSCAN_COUNT = 1;
const THROTTLE_DELAY = 100;

export const useScrollBasedChunks = ({
parentRef,
Expand Down Expand Up @@ -54,38 +51,45 @@ export const useScrollBasedChunks = ({
return {start, end};
}, [parentRef, tableRef, rowHeight, chunkSize, overscanCount, chunksCount]);

React.useEffect(() => {
const updateVisibleChunks = React.useCallback(() => {
const newRange = calculateVisibleRange();

if (newRange) {
setStartChunk(newRange.start);
setEndChunk(newRange.end);
}
}, [chunksCount, calculateVisibleRange]);
}, [calculateVisibleRange]);

React.useEffect(() => {
updateVisibleChunks();
}, [chunksCount, updateVisibleChunks]);

const handleScroll = React.useCallback(() => {
const newRange = calculateVisibleRange();
if (newRange) {
setStartChunk(newRange.start);
setEndChunk(newRange.end);
}
}, [calculateVisibleRange]);
updateVisibleChunks();
}, [updateVisibleChunks]);

React.useEffect(() => {
const throttledHandleZoom = rafThrottle(() => {
updateVisibleChunks();
});

window.addEventListener('resize', throttledHandleZoom);

return () => {
window.removeEventListener('resize', throttledHandleZoom);
};
}, [updateVisibleChunks]);

React.useEffect(() => {
const container = parentRef?.current;
if (!container) {
return undefined;
}

const throttledHandleScroll = throttle(handleScroll, THROTTLE_DELAY, {
leading: true,
trailing: true,
});
const throttledHandleScroll = rafThrottle(handleScroll);

container.addEventListener('scroll', throttledHandleScroll);
return () => {
container.removeEventListener('scroll', throttledHandleScroll);
throttledHandleScroll.cancel();
};
}, [handleScroll, parentRef]);

Expand Down
Loading