React useCallback Hook
React useCallback
'useCallback' is a React Hook that memoizes a callback function, preventing it from being recreated on every render.
This can be useful to optimize performance, especially in scenarios where callbacks are passed down to child components.
Here's a basic example of how to use 'useCallback':
import React, { useState, useCallback } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
// Regular callback function
const handleClick = () => {
setCount(count + 1);
};
// Memoized callback using useCallback
const memoizedHandleClick = useCallback(() => {
setCount(count + 1);
}, [count]); // Dependency array, re-create the callback only when 'count' changes
return (
<div>
<p>Count: {count}</p>
{/* Regular callback */}
<button onClick={handleClick}>Increment</button>
{/* Memoized callback */}
<button onClick={memoizedHandleClick}>Increment Memoized</button>
</div>
);
};
export default MyComponent;
In this example