油门 /调试UseMemo值

发布于 2025-01-18 01:03:21 字数 887 浏览 2 评论 0原文

有没有什么方法可以使用 useMemo 来消除/限制 React 中的计算值?

我经常看到在 React 中创建去抖动/限制函数的解决方案,就像这个例子一样:

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

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

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

但我正在寻找的是一种去抖动/限制的方法,而不是函数,例如:

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

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

由于 veryBigArray 中的更改,App 将重新渲染很多次,其中 heavyCompulatedValue 不需要每次重新渲染时都是最新的。

因此,我正在寻找一种方法,使我的 useMemo 仅计算间隔(节流)上的实际值,而不引入新状态。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文