Skip to content

12.useMemo及useCallback源码实现

js

export function useMemo(dataFactory, deps = []) {
  let [preData, preDeps] = states[hookIndex] || [null, null];
  if(!states[hookIndex] || deps.some((item, index) => item !== preDeps[index])){
    let newData = dataFactory()
    states[hookIndex++] = [newData, deps]
    return newData
  }
  hookIndex ++
  return preData
}

export function useCallback(callback, deps) {
  let [preCallback, preDeps] = states[hookIndex] || [null, null];
  if(!states[hookIndex] || deps.some((item, index) => item !== preDeps[index])){
    states[hookIndex++] = [callback, deps]
    return callback
  }
  hookIndex ++
  return preCallback
}

基于 VitePress 构建