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?
Advertisement
Answer
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]);