Understanding the Terms: useMemo vs useCallback
useMemo
useMemo is very similar to useCallback. It accepts a function and a list of dependencies. But the difference between useMemo and useCallback is that useMemo returns the memo-ized value returned by the passed function. It only recalculates the value when one of the dependencies changes. It’s very useful if you want to avoid expensive calculations on every render when the returned value isn’t changing.
In the following demo, we have a component with two states: one stores a number, and the other one a boolean.
We need to do some calculations on the number we have in our state, so we call our addFive
function and render the result.
const plusFive = (num) => {
console.log("I was called!");
return num + 5;
};export default function App() {
const [num, setNum] = useState(0);
const [light, setLight] = useState(true);
const numPlusFive = useMemo(() => plusFive(num), [num]);
return (
...
https://codesandbox.io/s/use-memo-134kiq?file=/src/App.js:365-376
useCallback
useCallback is a react hook that returns a memorized callback when passed a function and a list of dependencies that set the parameters. It’s useful when a component is passing a callback to its child component in order to prevent rendering. It as it were adjusts the callback when one of its conditions is altered.
In the demo below, we have a child component (<SomeComp>) that receives as a prop, a function we created inside the parent component (<App>). Note this function is being used inside a useEffect hook, and since it’s listed as useEffect’s dependency, it’s being called again. Yes, even when we change other states or receive props, not related to our “plusFive” function.
To prevent our function from being recreated and change pointers on each render round, we can use useCallback
. This React hook receives two parameters: A function and an array of dependencies.
const App = () => {
const [num, setNum] = useState(0);
const [light, setLight] = useState(true);
const plusFive = useCallback(() => {
console.log("I was called!");
return num + 5;
}, [num]);
return (...
);
}const SomeComp = ({ someFunc }) => {
const [calcNum, setCalcNum] = useState(0);
useEffect(() => {
// In this scenatio, someFunc will change on every render, so this useEffect will run.
setCalcNum(someFunc());
}, [someFunc]);return <span> Plus five: {calcNum}</span>;
};
https://codesandbox.io/s/use-callback-mfeb57?file=/src/App.js
useMemo and useCallback Difference
Despite seeming very similar, there are different use cases for each. You should wrap functions with useCallback when passing a function as a dependency to other hooks or wrapping a functional component in React.Memo()
that accepts your method as a property. You can use useMemo when you are working on functions where the inputs gradually change, where data values aren’t large enough to cause memory issues, or if the parameters are large enough so that the cost of comparison doesn’t outweigh the use of the wrapper.
useCallback works well in instances where the code would otherwise be recompiled with every call. Memorizing the results can decrease the cost of calling functions over and over again when the inputs change gradually over time.
Conclusion
If a function does not receive a previously used set of parameters, useMemo prohibits it from being executed again. It returns the results of a function. Use it when you wish to avoid calling some heavy or expensive processes on each render.
Using useCallback prevents a function from being re-created depending on a list of dependencies. It returns the function itself. Use it when you want to propagate it to child components, and prevent from a costly function from re-running.
For more updates on such topics, please follow our LinkedIn page- FrontEnd Studio