我不明白为什么useCallback
每次更新其中一个 deps 时,总是返回一个新的引用。它导致许多重新渲染React.memo()
本来可以避免的。
此实施有什么问题(如果有)useCallback
?
export function useCallback(callback) {
const callbackRef = useRef();
callbackRef.current = callback;
return useState(() =>
(...args) => callbackRef.current(...args)
)[0];
}
使用它而不是内置实现肯定会对性能产生显着的积极影响。
自己的结论:
没有理由不使用使用 ref 而不是构建的实现只要您意识到其中的含义,即,正如 @Bergy 所指出的,您就无法存储回调以供以后使用(在setTimeout
例如)并期望回调具有与同步调用它相同的效果。
然而,在我看来,这是首选行为,所以没有缺点????。
Update:
有一个 React RFC 引入了一个内置的钩子来做到这一点。它将被称为useEvent https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
此实施有什么问题(如果有)useCallback
?
我怀疑当有人存储对您的回调的引用以供以后使用时,会产生意想不到的后果,因为它会改变它正在做的事情:
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] /cdn-cgi/l/email-protection/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected] /cdn-cgi/l/email-protection/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)
与本土人useCallback
,存储在的函数printerHistory
将是不同值的不同闭包,而在您的实现中,它们都是引用最新值的相同函数useCallback
参数,并且仅在每次调用时打印当前值。
如需更详细的说明,请参阅useEvent提议 https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#basic-example。肯定有这样的用例,比如solving https://stackoverflow.com/a/62005831/1048572 the stale https://stackoverflow.com/a/67117702/1048572 closure https://stackoverflow.com/q/55154186/1048572 problem https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function,但这与问题不同useCallback
solves.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)