简体   繁体   中英

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?

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.

UseMemo sample use:

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:

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:

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(() => {
   getCharacters()
  }, [input, getCharacters]);

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