useEffect
有与之相关的非常具体的计时方面,您可以在此处阅读。指定的函数将在渲染完成且 DOM 已更新后执行。这将在每次渲染后发生,其中第二个参数数组中指定的任何值发生更改。
useCallback
不会自动执行任何东西。它返回一个函数,任何需要触发它的代码都可以执行该函数。没有侦听导致执行回调的更改。数组值仅控制返回的函数实例。数组值不控制函数执行的时间。
一个关键用例是将此函数作为props传递给子组件以用作事件处理程序。useCallback
允许您定义一个内联函数以用作事件处理程序(因此它可以访问定义函数的上下文中的任何其他变量),而没有在每次渲染时将唯一的 prop 传递给子级的缺点。只要第二个参数数组中的值没有改变,就会返回与前一次渲染相同的函数。所以如果子组件是纯组件,就不会因为总是接收唯一的事件处理函数而被迫重新渲染。
没有 useCallback
const Parent = ()=> {
const [a, setA] = useState(null);
const eventHandler = ()=> {
// every render creates a unique instance of eventHandler
// even though it always does the same thing so long as 'a' hasn't changed
doSomethingWithA(a);
}
return <Child onClick={eventHandler}/>
}
和 useCallback
const Parent = ()=> {
const [a, setA] = useState(null);
const eventHandler = useCallback(()=> {
// A unique function instance is passed in to useCallback on every render, but
// eventHandler will be set to the first instance of this function
// (i.e. potentially an instance of the function that was passed to useCallback
// on a previous rendering) that was passed to useCallback
// for the current value of 'a'.
doSomethingWithA(a);
}, [a]);
return <Child onClick={eventHandler}/>
}
这篇文章提供了比 React 文档更多的关于 foruseCallback
和其他钩子用例的细节。
相关答案:React Hooks useCallback 的简单示例有问题