useCallback React: Performance Guide
useCallback is a Hook used for caching functions in order to address the issue of functions being recreated in function components, leading to unnecessary re-rendering of child components. Proper use of useCallback can improve performance and prevent unnecessary renders.
The useCallback function accepts two parameters: the first parameter is a function, and the second parameter is an array of dependencies. When the values in the dependency array change, the function will be recreated; otherwise, the cached function will be returned.
Here is an example demonstrating how to use useCallback correctly.
import React, { useState, useCallback } from 'react';
const App = () => {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<h1>{count}</h1>
<button onClick={handleClick}>Increase Count</button>
</div>
);
};
export default App;
In the example above, the handleClick function will be recreated when the count changes, otherwise it will return the cached function. This helps avoid unnecessary renders and improves performance.