The useCallback
hook in React is used for performance optimization by memoizing functions, which means it returns a memoized version of the callback function that only changes if one of the dependencies has changed. This can be particularly useful in preventing unnecessary re-renders in child components, especially when passing callbacks down as props.
Here's how you can use useCallback
:
jsxCopy codeimport React, { useCallback } from 'react';
function MyComponent() {
// Define a function that you want to memoize
const handleClick = () => {
console.log('Button clicked!');
};
// Use useCallback to memoize the function
const memoizedHandleClick = useCallback(handleClick, []);
return (
<div>
<button onClick={memoizedHandleClick}>Click me</button>
</div>
);
}
export default MyComponent;
In this example:
handleClick
function.useCallback
to memoize handleClick
.useCallback
is an array of dependencies. If any of these dependencies change, useCallback
will return a new memoized version of the function. If the array is empty ([]
), the function will only be created once and won't change for the lifetime of the component.By using useCallback
, you ensure that the function reference remains stable across renders as long as the dependencies remain unchanged. This can prevent unnecessary re-renders in child components that receive this function as a prop because React will recognize that the function reference hasn't changed and won't trigger a re-render unless other props have changed.