类似Vue的计算属性,当依赖项中的useState的数据改变,重新渲染函数时,
会重新调用函数,返回新的值,否则会一直使用缓存的旧值
主要是对返回结果进行缓存
1、引入
import React, {Component,useContext } from 'react';
2、使用
const memoizedValue = useMemo(() => { 不能传递参数
return x...;
}, [x]);
代码示例:
const set = new Set();
function App()
{
const [count, setCount] = useState(1);
const [memory, setMemory] = useState(set);
const [count2,setCount2]=useState(2);
const memoizedValue = useMemo(() => {
memory.add(count);
console.log(memory)
return count;
}, [count]);
set.add(memoizedValue);
console.log(memory)
console.log('渲染')
return <div>
<h4>{count}</h4>
<h4>{set.size}</h4>
<h4>{count2}</h4>
<h4>{memoizedValue}</h4>
<div>
<button onClick={() => setCount(count + 1)}>+</button>
<button onClick={()=>{ setCount2(count2+1);setMemory(memory.add(memoizedValue));}}>回调</button>
<button></button>
</div>
</div>;
}