The useCallback hook allows you to memoize a function so that it’s only re-created when its dependencies change. This can help improve performance by preventing unnecessary re-renders.
Here’s an example of how to use useCallback to memoize a function:
import React, { useState, useCallback } from 'react'; function SearchBar({ onSearch }) { const [query, setQuery] = useState(''); const handleQueryChange = useCallback(event => { setQuery(event.target.value); onSearch(event.target.value); }, [onSearch]); return ( <input type="text" value={query} onChange={handleQueryChange} /> ); }
In this example, we define a SearchBar component that takes an onSearch prop function. We use the useCallback hook to memoize the handleQueryChange function so that it’s only re-created when the onSearch function changes.