Home > Enterprise >  what is difference between useCallback and useMemo in react hooks?
what is difference between useCallback and useMemo in react hooks?

Time:05-31

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?

CodePudding user response:

useMemo and useCallback use memoization.

I like to think of memoization as remembering something.

While both useMemo and useCallback remember something between renders until the dependencies change, the difference is just what they remember.

useMemo will remember the returned value from your function.

useCallback will remember your actual function.

In one line

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

CodePudding user response:

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 (e.g, 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]);
  • Related