In React, the useCallback
hook is used to return a memoized callback function. It is useful when you want to optimize the performance of a component by avoiding unnecessary re-renders.
Here’s a simple example of how to use the useCallback
hook:
import { useCallback } from 'react';
function MyComponent(props) {
const { data } = props;
// The useCallback hook takes a function and an array of dependencies as arguments
// and returns a memoized version of the function.
const memoizedCallback = useCallback(() => {
// This function will only be re-created if one of the dependencies has changed.
// Otherwise, the same function instance will be used.
doSomething(data);
}, [data]);
return <div onClick={memoizedCallback}>Click me</div>;
}
In this example, the memoizedCallback
function will only be re-created if the data
prop has changed. This can help to avoid unnecessary re-renders of the MyComponent
component if the memoizedCallback
function is passed as a prop to a child component.
useCallback
is a hook in React that allows you to memoize a function. This means that the function will only be re-created if one of its dependencies has changed. This can be useful in a number of situations, such as:
- When you pass a callback prop to a performance-critical child component, and you don’t want the child component to re-render every time the parent re-renders.
- When you have an expensive operation that you don’t want to perform on every render, such as an API call or a deep object comparison.
Here’s an another example of how you might use useCallback
:
const MyComponent = ({ onClick }) => {
const handleClick = useCallback(() => {
console.log('clicked');
}, []);
return <button onClick={handleClick}>Click me</button>;
};
In this example, the handleClick
function will only be re-created if the component re-renders with a different onClick
prop.
When to use React useCallback() ?
You should use useCallback
when you have a callback function that is passed as a prop to a child component, and that child component should not re-render when the parent component re-renders unless the callback has changed.
For example, when you have a child component that renders a list of items, and the parent component is responsible for handling the delete action, you can use useCallback to create a memoized version of the callback function that is passed as a prop to the child component. This way, the child component only re-renders when the delete action callback changes and not every time the parent component re-renders.
It is also useful when you have a callback function that is computationally expensive and you want to avoid re-creating it on every render.