In react hook useCallback function used for
useCallback
is a React Hook that memoizes a callback function. It is used to optimize performance by preventing unnecessary re-renders in certain situations. When you use ituseCallback
, it memoizes the callback function so that it doesn't get recreated on every render unless its dependencies change.
Here's an example of how to use ituseCallback
:
import React, { useState, useCallback } from 'react';
const CallbackExample = () => {
// State to track the count
const [count, setCount] = useState(0);
// Callback function without useCallback
const handleClickWithoutCallback = () => {
console.log('Button clicked! Count:', count);
// Do something with the count, but note that this function
// is recreated on every render.
};
// Callback function with useCallback
const handleClickWithCallback = useCallback(() => {
console.log('Button clicked! Count:', count);
// Do something with the count
}, [count]); // Dependency array: only recreate the function if count changes
return (
<div>
<p>Count: {count}</p>
{/* Button without useCallback */}
<button onClick={handleClickWithoutCallback}>
Click without useCallback
</button>
{/* Button with useCallback */}
<button onClick={handleClickWithCallback}>
Click with useCallback
</button>
{/* Button to update the count */}
<button onClick={() => setCount(count + 1)}>
Increment Count
</button>
</div>
);
};
export default CallbackExample;
In this example:
We have a
count
state variable that we want to use inside a callback function.handleClickWithoutCallback
is a callback function without usinguseCallback
. It gets recreated on every render, which can lead to unnecessary re-renders of components that use this callback.handleClickWithCallback
is a callback function created usinguseCallback
. The second argument touseCallback
is an array of dependencies. The callback is only recreated if the dependencies change. In this case, the dependency iscount
, so the callback is recreated only whencount
changes.
Conclusion:
This is important callback function used for momoizing and stops re-rendering.