组件重新渲染时缓存计算的结果。
实例:count1计算斐波那契数列,count2和count1可以触发数值变化。使用memo可以使只有在count1变化时触发斐波那契数列计算函数,而count2变化时不触发斐波那契数列计算函数。
import { useMemo } from "react";
import { useState } from "react";
function fib(n) {
console.log('计算函数执行')
if (n < 3) {
return 1
}
return fib(n - 1) + fib(n - 2)
}
function App() {
const [count1, setCount1] = useState(0)
const [count2, setCount2] = useState(0)
console.log('组件重新渲染')
const result = useMemo(() => {
return fib(count1)
}, [count1])
return (
<div className="App">
<button onClick={() => { setCount1(count1 + 1) }}>change count1: {count1}</button>
<button onClick={() => { setCount2(count2 + 1) }}>change count2: {count2}</button>
result: {result}
</div>
)
}
export default App