useMemo 钩子的用例 [英] Usecase for useMemo hook

查看:12
本文介绍了useMemo 钩子的用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 React 的 useMemo 文档.他们说当你需要计算昂贵的计算时使用它.

Looking at React's useMemo documentation. They say to use it when you need to compute an expensive calculation.

这种优化有助于避免每次渲染时进行昂贵的计算.

This optimization helps to avoid expensive calculations on every render.

我查看了他们提供的 memoized link 以及什么我的理解是你可以把它想象成一个缓存.

I looked at the memoized link they provide and what I understood is that you can think of it like an cache.

我不是计算机科学专家,但我知道记忆法是计算fibonacci

I'm not an expert at computer science, but I know that memoization is a good optimization for calculating fibonacci

我仍在尝试更好地理解为什么以及如何使用 useMemo,但我仍然不清楚一些事情.

I'm still trying to understand better why and how to use useMemo, but a few things are still unclear to me.

  • 什么被认为是昂贵的计算?
  • 有人可以给出真实的 react 示例吗?
  • 在什么情况下 useMemo 有利于性能优化?
  • What is considered expensive calculations?
  • Can someone give real react examples?
  • In what cases useMemo is good for performance optimization?

推荐答案

首先你应该知道你只能记住纯函数,即输出完全取决于其参数的函数.

First of all you should know that you can only memoize pure functions, that is functions whose output purely depends on its arguments.

所以简而言之,当您知道大多数情况下输入保持不变并且您不想不必要地一次又一次地重新计算相同输入的结果时,您会进行记忆,特别是当计算成本很高时,这可能意味着需要计算的数据集很大

So in short, you would do memoization when you know that most often input remains the same and you wouldn't want to unnecessarily recalculate the result again and again for the same input specially when the calculation is expensive which may mean that the data-set on which computation needs to be performed is large

  • 当您尝试从大型数组中过滤数据时,React 可能是使用记忆化的一个例子.

  • A case of using memoization is React may be when you are trying to filter data from a large array.

另一种情况是,您希望将基于某些参数的嵌套对象转换为其他对象或数组.

Another case would be when you wish to transform a nested object based on some parameters into other object or array.

在这种情况下,useMemo 真的很有帮助.如果数组和过滤条件在重新渲染时保持不变,则不会再次进行计算,而是从缓存中返回先前计算的数据

In such as case useMemo is really helpful. If the array and the filter criteria remains the same across re-renders, the calculation is not done again instead the previously calculated data is returned from the cache

这篇关于useMemo 钩子的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆