Skip to main content

useMemo

用于优化性能,在组件重新渲染时,返回一个记忆化的值,以避免不必要的计算和重复工作。

index.tsx
import React, { useState, useMemo } from 'react';

function MyApp() {
const [count, setCount] = useState(0);

const factorial = useMemo(() => {
let value = 0;
for (let i = 0; i <= count; i++) {
value += i;
}
return value;
}, [count]);

return (
<div>
<div onClick={() => setCount(count + 1)}>{count}</div>
<div>{factorial}</div>
</div>
);
}

export default MyApp;