1. useMemo的使用
useMemo和useEffect 的使用基本上一样
import React, { useState, memo, useMemo, useCallback } from 'react'
const Child = memo((props) => {
const date = new Date()
return (
<div>
当前时间:{date.getHours()} : {date.getMinutes()} : {date.getSeconds()}
</div>
)
})
const Parent = () => {
const [count, setCount] = useState(0)
const [clickTimeCount, setClickTimeCount] = useState(0)
const timeOption = useMemo(() => {
return { clickTimeCount }
}, [clickTimeCount])
return (
<div>
<div>count: {count}</div>
<button onClick={() => {
setCount(count + 1)
}}>+1</button>
<button onClick={() => {
setClickTimeCount(clickTimeCount + 1)
}}>get current time</button>
<Child count={timeOption}/>
</div>
)
}
function App() {
return <div><Parent /></div>
}
export default App
useMemo的好处
- 对子组件进行一定程度的优化
- 在useMemo函数内通过复杂计算获取当前值得时候,不需要再父组件每次更新的时候重新计算,只要在依赖项发生变化的时候计算即可
网友评论