useMemo
memoizes expensive computations so they don't re-run on each render.- Implementation: useMemo
useMemo
runs on every render to compare the previous and current value of the dependency array.useMemo
callback function is only called if the dependency array has changed.
- CodeSandBox: useMemo hook: Re-rendering won't re-compute value in
useMemo
hook unless desired (as indicated via the dependency array)
- Main difference: callback function of
useMemo
is called once when rendering. Callback function ofuseCallback
is called when the callback is invoked. useCallback
memoizes the function itself, whileuseMemo
memoizes the result of the function.
Example:
/**
* first argument of `useMemo` is called every time `someProp` changes
*/
const myValue = useMemo(() => {
console.log("my value got memoized");
return "stored value = " + someProp;
}, [someProp]);
useEffect(() => {
// calling `myValue` will not re-run the `useMemo` callback function
setTimeout(() => {
console.log("setTimeout", myValue);
console.log("setTimeout", myValue);
console.log("setTimeout", myValue);
console.log("setTimeout", myValue);
console.log("setTimeout", myValue);
}, 2000);
}, [myValue]);