useMemo以及部分源码
const [count,setCount] = useState(0)
const add = useCallback(() => {
count++
setCount(count)
}, [count])
const getCount = useMemo(()=>{
console.log(count)
},[count])
const getOldCount = useMemo(()=>{
console.log(count)
},[])
function mountMemo(nextCreate,deps) {
const hook = mountWorkInProgressHook()
const nextDeps = deps === undefined ? null : deps
const nextValue = nextCreate()
hook.memoizedState = [nextValue, nextDeps]
return nextValue
}
function updateMemo<T>(nextCreate,deps) {
const hook = updateWorkInProgressHook()
const nextDeps = deps === undefined ? null : deps
const prevState = hook.memoizedState
if (prevState !== null) {
if (nextDeps !== null) {
const prevDeps = prevState[1]
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0]
}
}
}
const nextValue = nextCreate()
hook.memoizedState = [nextValue, nextDeps]
return nextValue
}