React useCallback 与组件内部和外部声明的纯函数之间的区别

问题描述 投票:0回答:1

这两种方法有区别吗?:

// outside component
const magicIdx = (i) => (i - 1) / 3

//inside component
const calcIdxOut = useCallback(magicIdx, [])
const calcIdxIn = useCallback((i) => (i - 1) / 3, [])

在组件外部定义一个纯函数并在没有依赖关系的 useCallback 中使用它有什么区别吗?

reactjs react-hooks
1个回答
1
投票

useCallback
与在组件外部声明的函数一起使用是没有意义的。
useCallback
的目的是为函数提供引用稳定性,即使该函数在技术上每次渲染时都会重新定义。由于这仅适用于在组件内部定义的函数,因此它在这里没有任何用处。 // Stable reference - only declared once function example() {} function App() { // Unstable reference - redeclared each time App renders function example2() {} // Stable reference - even though example2 changes, // example3 reference only changes if dependencies to useCallback change. const example3 = useCallback(example2, []); }

因此,如果上面的示例有意义,您会注意到 
example

已经稳定,因此没有理由在其上使用

useCallback
你的函数并不昂贵,所以除非这里的目的是防止记忆的子组件重新渲染,否则引用稳定性实际上并不是一个大问题。

© www.soinside.com 2019 - 2024. All rights reserved.