用例备注挂钩 [英] Usecase for useMemo hook

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

问题描述

查看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 链接,据我了解,您是可以将其视为缓存.

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.

  • 什么被认为是expensive calculations?
  • 有人可以给出真实的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

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

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