Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which is better to use useMemo or useCallback when the function comes as a dependency on useMemo dependency array

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])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading