I use this pattern sometimes where I declare a curried function inside useCallback.
const Child = ({ handleClick }) => {
return (
<>
<button onClick={handleClick("foo")}>foo</button>
<button onClick={handleClick("lorem")}>lorem</button>
</>
);
};
export default function App() {
const [state, setState] = useState("");
const handleClick = useCallback(
(newState) => () => {
setState(newState);
},
[]
);
return (
<div className="App">
<Child handleClick={handleClick} />
<p>{state}</p>
</div>
);
}
because I want to pass arguments from JSX to the event handlers and to avoid multiple handlers.
When the component rerenders, handleClick will be called and the function that is returned will be assigned to the onClick prop, but will it be a new function every time or will the nested function also get memoized by useCallback?
PS: This is a simple example. Assume a useCallback usage with multiple dependencies