useMemo使用场景:消耗非常大的计算,例如递归
import { useMemo, useState } from 'react';
// 缓存:消耗非常大的计算,例如递归
function fib(n){
console.log('fib');
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])
// const result = fib(count1);
console.log('组件重新渲染了');
return (
<div className="home">
<button type="primary" onClick={()=>setCount1(count1 + 1)}>count1值{count1}</button><br />
<button type="primary" onClick={()=>setCount2(count2 + 1)}>count2值{count2}</button><br />
{result}
</div>
)
}
export default App