react-hooks
react-hooks copied to clipboard
Investigate scroll event debouncing
Motivation
Scroll events may be fired at a high frequency, without taking unwanted framerate drops into account.
Details
A similar problem is present for virtual scrolling/windowing approaches. We should follow the thread below for further information:
Issue #113 could provide a partial solution:
function useDebouncedWindowScrollCoords() {
const coords = useWindowScrollCoords();
const [debouncedCoords, setDebouncedCoords] = useState(coords);
const isChanging = useChanging(coords, 150);
useEffect(() => {
if (!isChanging) setDebouncedCoords(coords);
}, [isChanging]);
return debouncedCoords;
}
The main drawback is that useWindowScrollCoords still features useState under the hood, which would cause unnecessary rerenders.
The code above could be made generic:
function useDebounce<T>(value: T, groupingIntervalMs?: number) {
const [debouncedValue, setDebouncedValue] = useState(value);
const isChanging = useChanging(value, groupingIntervalMs);
useEffect(() => {
if (!isChanging) setDebouncedValue(value);
}, [isChanging]);
return debouncedValue;
}
After all, rerenders are not so problematic, especially with some room for additional optimization.