1
1
import React from 'react' ;
2
2
3
- import { throttle } from 'lodash' ;
4
-
5
- import { calculateElementOffsetTop } from './utils' ;
3
+ import { calculateElementOffsetTop , rafThrottle } from './utils' ;
6
4
7
5
interface UseScrollBasedChunksProps {
8
6
parentRef : React . RefObject < HTMLElement > ;
@@ -14,7 +12,6 @@ interface UseScrollBasedChunksProps {
14
12
}
15
13
16
14
const DEFAULT_OVERSCAN_COUNT = 1 ;
17
- const THROTTLE_DELAY = 100 ;
18
15
19
16
export const useScrollBasedChunks = ( {
20
17
parentRef,
@@ -54,38 +51,45 @@ export const useScrollBasedChunks = ({
54
51
return { start, end} ;
55
52
} , [ parentRef , tableRef , rowHeight , chunkSize , overscanCount , chunksCount ] ) ;
56
53
57
- React . useEffect ( ( ) => {
54
+ const updateVisibleChunks = React . useCallback ( ( ) => {
58
55
const newRange = calculateVisibleRange ( ) ;
59
-
60
56
if ( newRange ) {
61
57
setStartChunk ( newRange . start ) ;
62
58
setEndChunk ( newRange . end ) ;
63
59
}
64
- } , [ chunksCount , calculateVisibleRange ] ) ;
60
+ } , [ calculateVisibleRange ] ) ;
61
+
62
+ React . useEffect ( ( ) => {
63
+ updateVisibleChunks ( ) ;
64
+ } , [ chunksCount , updateVisibleChunks ] ) ;
65
65
66
66
const handleScroll = React . useCallback ( ( ) => {
67
- const newRange = calculateVisibleRange ( ) ;
68
- if ( newRange ) {
69
- setStartChunk ( newRange . start ) ;
70
- setEndChunk ( newRange . end ) ;
71
- }
72
- } , [ calculateVisibleRange ] ) ;
67
+ updateVisibleChunks ( ) ;
68
+ } , [ updateVisibleChunks ] ) ;
69
+
70
+ React . useEffect ( ( ) => {
71
+ const throttledHandleZoom = rafThrottle ( ( ) => {
72
+ updateVisibleChunks ( ) ;
73
+ } ) ;
74
+
75
+ window . addEventListener ( 'resize' , throttledHandleZoom ) ;
76
+
77
+ return ( ) => {
78
+ window . removeEventListener ( 'resize' , throttledHandleZoom ) ;
79
+ } ;
80
+ } , [ updateVisibleChunks ] ) ;
73
81
74
82
React . useEffect ( ( ) => {
75
83
const container = parentRef ?. current ;
76
84
if ( ! container ) {
77
85
return undefined ;
78
86
}
79
87
80
- const throttledHandleScroll = throttle ( handleScroll , THROTTLE_DELAY , {
81
- leading : true ,
82
- trailing : true ,
83
- } ) ;
88
+ const throttledHandleScroll = rafThrottle ( handleScroll ) ;
84
89
85
90
container . addEventListener ( 'scroll' , throttledHandleScroll ) ;
86
91
return ( ) => {
87
92
container . removeEventListener ( 'scroll' , throttledHandleScroll ) ;
88
- throttledHandleScroll . cancel ( ) ;
89
93
} ;
90
94
} , [ handleScroll , parentRef ] ) ;
91
95
0 commit comments