简体   繁体   中英

React Docs and difference between useMemo and useCallback

useCallback

When I look at useCallback and useMemo, I see the same thing. 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.

From the code examples that I see online, it seems like useCallback is used naturally for callbacks and useMemo for non-callback related code. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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