The useCallback
hook is another useful React hook that is used to memoize a callback function, similar to useMemo
. It's particularly handy when you want to prevent unnecessary renders of child components that rely on functions passed as props.
Here's a basic explanation of how to use the useCallback
hook:
import React, { useState, useCallback } from 'react';
const ChildComponent = ({ onClick }) => {
console.log('ChildComponent rendered');
return <button onClick={onClick}>Click me</button>;
};
const ParentComponent = () => {
const [count, setCount] = useState(0);
// Using useCallback to memoize the click handler function
const handleClick = useCallback(() => {
console.log('Button clicked');
setCount(prevCount => prevCount + 1);
}, []); // An empty dependency array means the function won't change over time
return (
<div>
<p>Count: {count}</p>
<ChildComponent onClick={handleClick} />
</div>
);
};
const App = () => {
return <ParentComponent />;
};
export default App;
In this example:
-
We have a
ChildComponent
that takes anonClick
prop. -
The
ParentComponent
has a state variablecount
and a callback functionhandleClick
that increments the count when the button is clicked. -
The
useCallback
hook is used to memoize thehandleClick
function. By providing an empty dependency array ([]
), we indicate that the function does not depend on any variables from the component's scope and won't change over time. -
The
ChildComponent
renders a button that triggers theonClick
callback passed as a prop. -
When you click the button, the
handleClick
function is called, and the count is incremented. TheChildComponent
only re-renders if its props change, and thanks touseCallback
, the callback function is memoized and won't change between renders.
This can be especially useful when passing callbacks to child components. By memoizing the callback with useCallback
, you ensure that the child component doesn't unnecessarily re-render when the parent component renders. It's an optimization to consider when dealing with performance concerns in your React applications.