0

I have the following useEffect():

useEffect(() => {
if (portfolios && portfolios.length > 0) {
  const wLocation = portfolios.filter((portfolio: Portfolios) =>
    portfolio.organizations.some(organization => organization.locations ?? false),
  );
  const wOutLocation = portfolios.filter((portfolio: Portfolios) =>
    portfolio.organizations.every(organization => organization.locations ?? true),
  );
  setPortfoliosWOutLocation(getItemsWRGB(wOutLocation.map(portfolioFormatted)));
  setPortfoliosWLocation(getItemsWRGB(wLocation.map(portfolioFormatted)));
}}, [portfolios]);

One of my partners tell me that I could use useMemo in order to avoid re calculation in every render, so I did this:

const portfolioWLocation = useMemo(() => {
const wLocation = portfolios.filter((portfolio: Portfolios) =>
    portfolio.organizations.some(organization => organization.locations ?? false),
  );
return getItemsWRGB(wLocation.map(portfolioFormatted));}, [portfolios]);

const portfolioWOutLocation = useMemo(() => {
const wOutLocation = portfolios.filter((portfolio: Portfolios) =>
    portfolio.organizations.every(organization => organization.locations ?? true),
  );
return getItemsWRGB(wOutLocation.map(portfolioFormatted));}, [portfolios]);

Will not be the same since portfolios is the dependency for useMemo() and useEffect().

rigojr
  • 351
  • 2
  • 11

1 Answers1

0

In terms of performance, there is no difference between the two. Both will only be executed if at least one of their dependencies has changed.

But they each serve a different purpose.

useMemo() is used for memoizing a value that can later be used within the component, while useEffect() is used for performing side effects (usually for doing some DOM manipulations or updating the state).

In your case, it seems like you are trying to compute some value, so you should use useMemo().

If you use useEffect(), you will have to maintain a state with useState(), and this will indeed have a negative impact on the performance since it will trigger additional renders.

Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56