useMemo 返回的一个经过缓存的值,useMemo的值参与渲染
如果 useMemo返回一个函数,就等价于 useCallback
- useCallback只创建一次事件句柄
- useCallback是 useMemo的一种变体
function App(props) {
const [count, setCount] = useState(0)
// useMemo的值参与渲染
const plus = useMemo(() => {
return count * 2
}, [ count === 3])
// 等价于 useCallback(fn)
const onClick = useMemo(() =>{
return () => { console.log('')}
})
const onClick2 = useCallback(() => {
console.log('callback click')
}, [count])
}
useMemo循环依赖bug
useMemo循环依赖,会死循环,错误的用法❌
function App(props) {
const [count, setCount] = useState(0)
// useMemo的值参与渲染
const multi = useMemo(() => {
return count * 2
}, [ count === 3])
const plus = useMemo(() =>{
return multi + 10
}, [multi]) // ❌
}