Home > Software design >  Which is better to use useMemo or useCallback when the function comes as a dependency on useMemo dep
Which is better to use useMemo or useCallback when the function comes as a dependency on useMemo dep

Time:09-29

I have a piece of code wrapped in useMemo that uses a function as a dependency that returns some data, is it worth using useMemo in this case since we return data, or is it better to useCallback

Example:

 // useMemo vs useCallback ?
 const getConfigs = useCallback((configs)=> {
   return configs.filter(...some filtering logic)
 }, [])

const getConfigs = useMemo(()=> {
   return configs.filter(...some filtering logic)
 }, [props.configs])

 const someMemoData = useMemo(()=>{
   return {
     names: props.names,
     configs: getConfigs(props.configs) or getConfigs in case useMemo
  }
 }, [props.names, getConfigs, props.configs])

CodePudding user response:

If you return data use useMemo

If you return function use useCallback

They both accept same parameters. Their first argument is a callback. The only difference is that:

useMemo(cb) returns cb()
useCallback(cb) returns cb

useCallback(() => {}) is same as useMemo(() => () => {})

Your getConfigs returns a function, so better use useCallback for it. While someMemoData returns object, use useMemo

  • Related