Skip to content

Commit b70ac88

Browse files
perf(ui): throttle page changes
Previously you could spam the next/prev buttons and really thrash the server. Throttled to 500ms, which feels like a happy medium between responsive and not-thrash-y.
1 parent 24609da commit b70ac88

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

invokeai/frontend/web/src/features/gallery/hooks/useGalleryPagination.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';
22
import { selectListImagesQueryArgs } from 'features/gallery/store/gallerySelectors';
33
import { offsetChanged } from 'features/gallery/store/gallerySlice';
4+
import { throttle } from 'lodash-es';
45
import { useCallback, useEffect, useMemo } from 'react';
56
import { useListImagesQuery } from 'services/api/endpoints/images';
67

@@ -80,32 +81,41 @@ export const useGalleryPagination = () => {
8081
return offset > 0;
8182
}, [count, offset]);
8283

84+
const onOffsetChanged = useCallback(
85+
(arg: Parameters<typeof offsetChanged>[0]) => {
86+
dispatch(offsetChanged(arg));
87+
},
88+
[dispatch]
89+
);
90+
91+
const throttledOnOffsetChanged = useMemo(() => throttle(onOffsetChanged, 500), [onOffsetChanged]);
92+
8393
const goNext = useCallback(
8494
(withHotkey?: 'arrow' | 'alt+arrow') => {
85-
dispatch(offsetChanged({ offset: offset + (limit || 0), withHotkey }));
95+
throttledOnOffsetChanged({ offset: offset + (limit || 0), withHotkey });
8696
},
87-
[dispatch, offset, limit]
97+
[throttledOnOffsetChanged, offset, limit]
8898
);
8999

90100
const goPrev = useCallback(
91101
(withHotkey?: 'arrow' | 'alt+arrow') => {
92-
dispatch(offsetChanged({ offset: Math.max(offset - (limit || 0), 0), withHotkey }));
102+
throttledOnOffsetChanged({ offset: Math.max(offset - (limit || 0), 0), withHotkey });
93103
},
94-
[dispatch, offset, limit]
104+
[throttledOnOffsetChanged, offset, limit]
95105
);
96106

97107
const goToPage = useCallback(
98108
(page: number) => {
99-
dispatch(offsetChanged({ offset: page * (limit || 0) }));
109+
throttledOnOffsetChanged({ offset: page * (limit || 0) });
100110
},
101-
[dispatch, limit]
111+
[throttledOnOffsetChanged, limit]
102112
);
103113
const goToFirst = useCallback(() => {
104-
dispatch(offsetChanged({ offset: 0 }));
105-
}, [dispatch]);
114+
throttledOnOffsetChanged({ offset: 0 });
115+
}, [throttledOnOffsetChanged]);
106116
const goToLast = useCallback(() => {
107-
dispatch(offsetChanged({ offset: (pages - 1) * (limit || 0) }));
108-
}, [dispatch, pages, limit]);
117+
throttledOnOffsetChanged({ offset: (pages - 1) * (limit || 0) });
118+
}, [throttledOnOffsetChanged, pages, limit]);
109119

110120
// handle when total/pages decrease and user is on high page number (ie bulk removing or deleting)
111121
useEffect(() => {

0 commit comments

Comments
 (0)