Optimize usage of useScrollListener and useTransactionsSearch (#5690)

This commit is contained in:
Joel Jeremy Marquez
2025-09-05 12:26:05 -07:00
committed by GitHub
parent de2966a06c
commit 58bc14e1b3
5 changed files with 45 additions and 17 deletions

View File

@@ -190,6 +190,12 @@ export function ScrollProvider<T extends Element>({
);
}
/**
* A hook to register a listener when the user scrolls within a ScrollProvider.
*
* @param listener The scroll listener to register. It is important to wrap this function
* in useCallback to avoid unnecessary unregistering and reregistering on each render.
*/
export function useScrollListener(listener: ScrollListener) {
const context = useContext(ScrollContext);
if (!context) {

View File

@@ -149,13 +149,18 @@ export function MobileNavTabs() {
<div key={idx} style={navTabStyle} />
));
useScrollListener(({ isScrolling, hasScrolledToEnd }) => {
if (isScrolling('down') && !hasScrolledToEnd('up')) {
hide();
} else if (isScrolling('up') && !hasScrolledToEnd('down')) {
openDefault();
}
});
useScrollListener(
useCallback(
({ isScrolling, hasScrolledToEnd }) => {
if (isScrolling('down') && !hasScrolledToEnd('up')) {
hide();
} else if (isScrolling('up') && !hasScrolledToEnd('down')) {
openDefault();
}
},
[hide, openDefault],
),
);
const bind = useDrag(
({

View File

@@ -139,11 +139,16 @@ export function TransactionList({
[dispatchSelected, onOpenTransaction, selectedTransactions],
);
useScrollListener(({ hasScrolledToEnd }) => {
if (hasScrolledToEnd('down', 100)) {
onLoadMore?.();
}
});
useScrollListener(
useCallback(
({ hasScrolledToEnd }) => {
if (hasScrolledToEnd('down', 100)) {
onLoadMore?.();
}
},
[onLoadMore],
),
);
return (
<>

View File

@@ -1,4 +1,4 @@
import { useState, useMemo, useEffect } from 'react';
import { useState, useMemo, useEffect, useRef } from 'react';
import { debounce } from 'lodash';
@@ -25,21 +25,27 @@ export function useTransactionsSearch({
}: UseTransactionsSearchProps): UseTransactionsSearchResult {
const [isSearching, setIsSearching] = useState(false);
const updateQueryRef = useRef(updateQuery);
updateQueryRef.current = updateQuery;
const resetQueryRef = useRef(resetQuery);
resetQueryRef.current = resetQuery;
const updateSearchQuery = useMemo(
() =>
debounce((searchText: string) => {
if (searchText === '') {
resetQuery();
resetQueryRef.current?.();
setIsSearching(false);
} else if (searchText) {
resetQuery();
updateQuery(previousQuery =>
resetQueryRef.current?.();
updateQueryRef.current(previousQuery =>
queries.transactionsSearch(previousQuery, searchText, dateFormat),
);
setIsSearching(true);
}
}, delayMs),
[dateFormat, delayMs, resetQuery, updateQuery],
[dateFormat, delayMs],
);
useEffect(() => {

View File

@@ -0,0 +1,6 @@
---
category: Maintenance
authors: [joel-jeremy]
---
Optimize usage of useScrollListener and useTransactionsSearch