'throttle / debounce useMemo value

Are there any ways to debounce/throttle computing values in React with useMemo?

I often see solutions to create debounced/throttled functions in React, like in this example:

const debouncedEventHandler = useMemo(
  () => debounce(eventHandler, 300),
  []
);

const throttledEventHandler = useMemo(
  () => throttle(eventHandler, 300),
  []
);

<button onClick={debouncedEventHandler}>Click Me</button>

But what I'm looking for is a way to debounced/throttled values, instead of functions, like:

const App = ({ veryBigArray }) => {
  // Throttle this value
  const heavyComputedValue = useMemo(
    () => veryBigArray.reduce( ... ),
    [veryBigArray]
  );

  return <div>{heavyComputedValue}</div>
}

The App will be re-rendering a lot because of the changes in this veryBigArray, where the heavyComputedValue does not need to be up-to-date on every re-render.

So I'm finding a way to make my useMemo only compute the actual value on an interval (throttle), without introducing a new state.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source