useCallback
1. 说明
- useCallback 可以让你在函数组件中 缓存计算函数
2. 语法
2.1 语法格式
const fnA = useCallback(fnB, [a])
2.2 语法说明
- useCallback 会将我们传递给它的函数fnB返回,并且将这个结果fnA 缓存;
- 当依赖a变更时,会返回新的函数。
把内联回调函数及依赖项数组作为参数传入
useCallback
,它将返回该回调函数的 memoized 版本,该回调函数仅在某个依赖项改变时才会更新。当你把回调函数传递给经过优化的并使用引用相等性去避免非必要渲染(例如shouldComponentUpdate
)的子组件时,它将非常有用。
3. 使用
// const inputChange = e => {
// console.log(e.target.value)
// }
// 这里面的箭头函数 依赖 count
// 如果 count 有变化, 就会创建一个新的 ()=>{}
// 如果 count 没有变化,
const inputChange = useCallback(() => {
console.log(count)
}, [count])
return (
<div>
<div>函数组件 - {count}</div>
<input type="text" onChange={inputChange} />
<button onClick={() => setCount(count + 1)}>改count</button>
<button onClick={() => setOther(other + 1)}>改干扰项</button>
</div>
)
4. 验证
- 返回的是函数,我们无法很好的判断返回的函数是否变更,所以我们可以借助ES6新增的数据类型Set来判断,
// 创建一个 全局的 set
const set = new Set();
// 缓存函数
const inputChange = useCallback(e => {
console.log('input获取的值', e.target.value)
}, [])
// 如果 地址一样 是不会添加的 地址不一样才会添加
set.add(inputChange)
console.log('长度', set.size)
5. 使用场景
//2. 创建组件
const App = () => {
const [count, setCount] = useState(0)
// 干扰
const [other, setOther] = useState(0)
const inputChange = useCallback(() => {
console.log(count)
}, [count])
set.add(inputChange)
console.log('set个数', set.size)
return (
<div>
<div>
函数组件 - {count} - {other}
</div>
<input type="text" onChange={inputChange} />
<button onClick={() => setCount(count + 1)}>改1</button>
<button onClick={() => setOther(other + 1)}>改1</button>
<Child f={inputChange}></Child>
</div>
)
}
// memo 是缓存外界传来的函数 不变会不更新
// 自己如果不变的话 自己就不更新了
const Child = memo(({ f }) => {
console.log('child')
return <div>Child组件</div>
})