These two React hooks, useMemo
and useCallback
are useful when you’re dealing with expensive operations (that is, operations that are very complex and take a lot of time and resources, like CPU.)
If you include one of those expensive operations inside a React component, these costly tasks will run every time the component re-renders, making the application slower.
Those two hooks help to optimize the app by running the costly operation and storing the result in a cache. The next time the component re-renders, it won't run the operation. Instead, it will return the result from the cache.
This is how useMemo works
Let's suppose that we have this expensive operation and a React component that uses it:
function uselessExpensiveOperation(input) {
const someBigArray = [];
for (let i = 0; i < 5_000_000; i++) {
someBigArray.push(input * i);
}
return someBigArray;
}
function SomeReactComponent() {
const expensiveOperationResult = uselessExpensiveOperation(3);
const output = expensiveOperationResult
.slice(0, 5)
.map(number => <li key={ number }>{ number }</li>);
return <ul>{ output }</ul>;
}
This example function can take many seconds to run. It returns an array of 5,000,000 numbers in which the value of each number depends on the number you pass as an argument. If you use uselessExpensiveOperation
in a React component directly, every time React calls that component during the render process, it will run the expensive operation.
Now, this is what happens if you use the useMemo
hook to store the value in cache:
function SomeReactComponent() {
const expensiveOperationResult = useMemo(
function() {
return uselessExpensiveOperation(3);
},
[]
);
const output = expensiveOperationResult
.slice(0, 5)
.map(number => <li key={ number }>{ number }</li>);
return <ul>{ output }</ul>;
}
The first argument of useMemo
is the function that contains the expensive operation, and the second argument is an array of dependencies. If the value of any of the dependencies changes, React will delete the cache and will run the expensive task.
The idea of the dependencies array is that you should include the variables that your expensive operation needs. In the example, the expensive operation doesn't have any dependency, so the array is empty.
How to use the useCallback hook
This hook is very similar to useMemo
, but it stores functions in the cache. You could do it using useMemo
, but the syntax is a little easier with useCallback
:
function SomeReactComponent() {
const cachedFunction = useCallback(
function originalFunction() {
return "some value";
},
[]
);
return <div>{ cachedFunction() }</div>
}
Now, when should you use it? First, I'll explain a special React function, React.memo
. This function works like useMemo
, but stores React components in the cache to prevent unneeded rendering. This is how it works:
const cachedComponent = React.memo(
function SomeReactComponent(props) {
return <div>Hello, { props.firstName }!</div>
}
);
The component will be stored in the cache until some of the props change. If that happens, it will re-render it and store it in cache again.
But there's a problem if one of the props is a function that was created in a parent component. Each time the parent component re-renders, the inner function is created again, and is considered as a different function, even if the code hasn't changed.
Therefore, when you pass the "different" function as a prop to the cached component, it will trigger an unneeded re-render.
If you use the useCallback
hook, you create the function the first time the component is rendered only. When the component is rendered again it will just retrieve the function from the cache, and this time it will be the same function, and it won't trigger the re-rendering in the child component.
Don't overoptimize
A common mistake that some developers do is to use these hooks (and other optimization techniques) even when they're not needed, trying to prevent performance problems. But that's not recommended because it makes the code more complex (and therefore, harder to maintain) and in some cases, it even performs worse.
You should apply these techniques after you find a performance problem. When something isn't running as fast as you would like, investigate where the bottleneck is and optimize that part.
Free JavaScript Newsletter! Every other Monday, easy and actionable steps to level up your JavaScript skills. Click here to subscribe
Top comments (0)