Why can't `useCallback` always return the same ref
What is, if any, the problem with this implementation of
useCallback
?
I suspect it has unintended consequences when someone stores a reference to your callback for later, as it will change what it is doing:
const { Fragment, useCallback, useState } = React;
function App() {
const [value, setValue] = useState("");
const printer = useCallback(() => value, [value]);
return <div>
<input type="text" value={value} onChange={e => setValue(e.currentTarget.value)} />
<Example printer={printer} />
</div>
}
function Example({printer}) {
const [printerHistory, setHistory] = useState([]);
return <Fragment>
<ul>{
printerHistory.map(printer => <li>{printer()}</li>)
}</ul>
<button onClick={e => setHistory([...printerHistory, printer])}>Store</button>
</Fragment>
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
(Sure, in this simplified demo the printer
callback is nothing but a useless closure over the value
itself, but you can imagine a more complex case where one could select an individual history entry and would want to use a complicated on-demand computation in the callback)
With the native useCallback
, the functions stored in the printerHistory
would be distinct closures over distinct values, while with your implementation they would all be the same function that refers to the latest useCallback
argument and only prints the current value on every call.