useCallback
React’s useCallback Hook delivers a callback function that has been memoized.
Consider memoization to be the process of caching a value such that it does not have to be computed.
This allows us to segregate resource-intensive processes so that they do not run automatically with each render.
The useCallback Hook only runs when one of its dependencies is updated.
This can boost performance.
The useCallback and useMemo hooks are similar. The primary distinction is that useMemo returns a memoized value, whereas useCallback returns a memoized function. The useMemo chapter contains additional information.
Problem
One purpose to utilize useCallback is to prevent a component from re-rendering unless its properties change.
In this example, you may believe that the Todos component will not re-render unless the todos change.
This example is similar to the one in the React.memo section.
Example:
index.js:
------ Example MUKAVU -----
Todos.js:
const Todos = ({ todos }) => {
console.log("child render");
return (
<>
My Todos
{todos.map((todo, index) => {
return {todo}
;
})}
>
);
};
export default Todos;
When you click the increment button, the Todos component reloads.
If this component was complex, it may lead to performance concerns.
Solution
To address this, we can use memo.
Use memo to prevent the Todos component from repeatedly re-rendering.
Wrap the Todos component export with a memo.
Example
index.js:
------- Example MUKAVU -------
Todos.js:
import { memo } from "react";
const Todos = ({ todos }) => {
console.log("child render");
return (
<>
My Todos
{todos.map((todo, index) => {
return {todo}
;
})}
>
);
};
export default memo(Todos);
Now, the Todos component only re-renders when the todos supplied to it via props change.