How to memoize custom hooks to improve performance

Viewed 1211

Have below function which is common custom hook and called from multiple places.

How this can be memoized to improve performance. (While debug on browser then observed it called multiple times). It would be also fine if fields.forEach only memoized instead of all code under custom hooks'

I tried to add a function inside the hook but, I need to return result object instead of function.

export function useListObject(fields)
{
const allData = useGetAll();
const result = {};
fields.foreach((field) =>{
  ...
  ...
  ...
  result[field]= {key, value , parameters, names}
});
return result;
}

///// component called as below

const listData = useListObject(['state','country','categoryTypes','category']); 

//Is it possible to memoize here ? so no need to memoize within custom hooks.

1 Answers

You can use the useMemo hook provided by React to memoize the result of your forEach loop:

const result = useMemo(() => {
  const fieldData = {};

  fields.foreach((field) =>{
    ...
    ...
    ...
    fieldData[field] = { key, value , parameters, names }
  })
  
  return fieldData;
}, [fields]);

This way until fields changes, result will be memoized to whatever you return inside of the useMemo call.

Related