- useCallback React Hook returns a memoized version of a callback function for better performance
- Note: consider memoization as caching a value so that it does not need to be recalculated.
Here’s an example of using useCallback to improve performance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import React, { useState,useCallback } from 'react'; import ReactDOM from 'react-dom/client'; //App function component function App() { const [count, setCount] = useState(0); const plus= useCallback(() => setCount(c => c + 1), [setCount]); //useCallBack for better performance. return ( <div> <p>Count: {count}</p> <button onClick={plus}>+</button> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
useCallback is used to memoize the plus function. The function only changes if setCount changes, so it’s only re-created if setCount is changed. This can improve performance by avoiding unnecessary re-renders.