useCallback
is a hook in React that is used to memoize functions. It returns a memoized version of the callback function that only changes if one of the dependencies has changed. This can be useful in optimizing performance, especially when passing callbacks to child components that rely on reference equality to prevent unnecessary re-renders.
Here is an example of how to use useCallback
in React:
import React, { useCallback } from 'react'; const MyComponent = () => { const handleClick = useCallback(() => { console.log('Button clicked!'); }, []); return ( <button onClick={handleClick}>Click me</button> ); };
In the above example, the handleClick
function is memoized using useCallback
. The empty dependency array []
indicates that the function does not depend on any variables, so it will always return the same memoized function instance. This ensures that the handleClick
function is not recreated on every render, optimizing performance.
Note: The code provided above is in JavaScript format. To use it in an HTML file, you would need to include a script tag and wrap the JavaScript code within <script>
tags.