简体   繁体   English

跨组件的 useMemo 行为

[英]useMemo behaviour across components

In my component, I'm using useMemo to run and cache a somewhat expensive query to the browser runtime.在我的组件中,我使用useMemo来运行一个有点昂贵的查询并将其缓存到浏览器运行时。 So far, it has cut back dramatically on the time required for subsequent renders.到目前为止,它已经大大减少了后续渲染所需的时间。

However, the actual first render is still a problem.然而,实际的第一次渲染仍然是一个问题。 I'm rendering thousands of instances of my component at once, and it seems that the expensive query gets repeated unnecessarily.我一次渲染了我的组件的数千个实例,似乎不必要地重复了昂贵的查询。 The same query result could be used for a lot of those instances, as I'm using only two or three unique inputs for the query at once.相同的查询结果可以用于很多这样的实例,因为我一次只使用两个或三个唯一的输入进行查询。 The query could be considered pure, as it consistently returns the same result for the same inputs.可以将查询视为纯查询,因为它始终为相同的输入返回相同的结果。

I'm left wishing that the memoized return value was available to other instances of the same component, but the profiling data suggests that it is not.我希望记忆的返回值可用于同一组件的其他实例,但分析数据表明事实并非如此。

Is there a clean and sustainable way to ensure that a memoized result is shared across all calls to the same function, regardless of the originating component instance?是否有一种干净且可持续的方法来确保在对同一函数的所有调用之间共享记忆结果,而不管原始组件实例如何?

The state that is maintained by React hooks is specific to component instance where they are called. React hooks 维护的状态特定于调用它们的组件实例。

In order for useMemo or useCallback to have a common state for multiple component instances, they should occur in nearest common parent and be provided with context API to deeply nested children if needed.为了使useMemouseCallback具有多个组件实例的公共状态,它们应该出现在最近的公共父级中,并在需要时为深度嵌套的子级提供上下文 API。

In case it should behave in a different way, general-purpose memoization utility should be used, like Lodash memoize :如果它应该以不同的方式运行,应该使用通用的记忆工具,比如Lodash memoize

const expensiveFn = () => ...;

const memoizedExpensiveFn = _.memoize(expensiveFn);

It also allows to have control over cache storage:它还允许控制缓存存储:

memoizedExpensiveFn.Cache = ES6MapWithExpiration;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM