作用: 组件每次重新渲染的时候缓存计算的结果
使用场景: 消耗非常大的计算时
举个栗子: 有count1,count2,只想在count1变化时,才执行fn,看代码
import { useState, useMemo } from 'react'
function fib(n) {
console.log('计算函数执行了')
if (n < 3) return 1
return fib(n - 2) + fib(n - 1)
}
const App = () => {
const [count1, setCount1] = useState(0)
const [count2, setCount2] = useState(0)
const result = fib(count1)
console.log('组件被渲染了')
return (
<div>
<button onClick={ () => setCount1(count1 + 1) }>change count1{count1}</button>
<button onClick={ () => setCount1(count2 + 1) }>change count2{count2}</button>
{result}
</div>
)
}
上面代码,不管是点击count1还是点击count2, 计算函数fbi都会执行,那么要怎么做才能实现,只有count1变化时才执行计算函数,count2变化时,使用缓存计算值呢?
这就要用到useMemo了, 替换掉14行的代码,改造如下
import { useState, useMemo } from 'react'
function fib(n) {
console.log('计算函数执行了')
if (n < 3) return 1
return fib(n - 2) + fib(n - 1)
}
const App = () => {
const [count1, setCount1] = useState(0)
const [count2, setCount2] = useState(0)
const result = useMemo(() => {
return fib(count1)
}, [count1])
console.log('组件被渲染了')
return (
<div>
<button onClick={ () => setCount1(count1 + 1) }>change count1{count1}</button>
<button onClick={ () => setCount1(count2 + 1) }>change count2{count2}</button>
{result}
</div>
)
}