react-hooks icon indicating copy to clipboard operation
react-hooks copied to clipboard

Investigate scroll event debouncing

Open kripod opened this issue 6 years ago • 2 comments

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:

kripod avatar Sep 21 '19 09:09 kripod

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.

kripod avatar Oct 25 '19 15:10 kripod

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.

kripod avatar Oct 25 '19 16:10 kripod