简体   繁体   English

React Docs以及useMemo和useCallback之间的区别

[英]React Docs and difference between useMemo and useCallback

useCallback useCallback

When I look at useCallback and useMemo, I see the same thing. 当我查看useCallback和useMemo时,我看到的是同一件事。 You pass in a function and an array of dependencies. 您传入一个函数和一个依赖项数组。 That function is only re-run if a dependency changes. 仅当依赖项更改时,才重新运行该功能。

This line is added in at the end and I cannot make sense of it: useCallback(fn, deps) is equivalent to useMemo(() => fn, deps) I wish there was further explanation, it might help me understand the difference between these two functions. 此行添加在末尾,我无法理解: useCallback(fn, deps) is equivalent to useMemo(() => fn, deps)我希望有进一步的解释,它可能有助于我理解两者之间的区别这两个功能。

From the code examples that I see online, it seems like useCallback is used naturally for callbacks and useMemo for non-callback related code. 从我在网上看到的代码示例中,似乎useCallback自然用于回调,而useMemo用于非回调相关代码。 Are these functions only different in name? 这些功能只是名称不同吗? There must be something going on under the hood that is just not spelled out explicitly? 一定是某些事情没有被明确阐明? Does useCallback memoize the function reference while useMemo memoizes the returned result of the function? useCallback会记住函数引用,而useMemo会记住函数的返回结果吗?

The two usages below are functionally equivalent: 以下两种用法在功能上等效:

const fn = useCallback((n) => add(n, n), [add]);

const fn = useMemo(() => (n) => add(n, n), [add]);

useCallback is a special case of useMemo that you can use if there's no pre-computation involved in creating your callback. useCallbackuseCallback的一种特殊情况,如果创建回调时不涉及预计算,则可以使用useMemo

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

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