简体   繁体   English

react 钩子中的 useCallback 和 useMemo 有什么区别?

[英]what is difference between useCallback and useMemo in react hooks?

can you tell me.你能告诉我吗。 what is difference between useCallback() and useMemo() in react hooks and when is the function used or what are the examples?反应钩子中的useCallback()useMemo()有什么区别,什么时候使用该函数或示例是什么?

useMemo:使用备忘录:

A hook used to memorize a value , when certain values of the dependency array change.当依赖数组的某些值发生变化时,用于记忆一个的钩子。

Instead, useCallback memorizes a function, a callback , so when the component re-renders, you don't have to recompute the whole function.相反, useCallback 会记住一个函数,一个回调,因此当组件重新渲染时,您不必重新计算整个函数。

UseMemo sample use: UseMemo 示例使用:

For example, you want to calculate the total of the cart payment.例如,您要计算购物车付款的总额。 I'll memorize that total value, and only change it when the taxes percent changes too.我会记住该总值,并且仅在税收百分比也发生变化时才更改它。

const total = useMemo(() => taxes + subtotal, [taxes]);

UseCallBack sample use: UseCallBack 示例使用:

I want to perform various calls to an API, or a DB to search for certain values (eg, on a searchbar), but I don't want the component to recompute the function every time it renders, so I memorize the function:我想对 API 或 DB 执行各种调用以搜索某些值(例如,在搜索栏上),但我不希望组件在每次呈现时都重新计算函数,所以我记住了函数:

const getCharacters = useCallback(() => {
      if(input.trim() !== ""){
        const value = input.toLocaleLowerCase()
        const chars = Characters.filter((character)  => {
          return character.name.toLowerCase().includes(value)}
        )
        setCharacters(chars)
      }else {
        setCharacters([])
      }
  }, [input]);

Usually, useCallback is used when a useEffect hook is also needed, to mount an element when certain dependency changes:通常,当还需要一个 useEffect 钩子时,使用 useCallback 来在某些依赖项发生变化时挂载一个元素:

useEffect(() => {
   getCharacters()
  }, [input, getCharacters]);

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

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