Search code examples
reactjstypescriptreact-hooks

useMemo: how should we memoize undefined API response


What is correct 1 or 2

1:

 const list =
    useMemo(
      () =>
        data?.items?.map((i) => ({
          label: i.email as string,
          value: i.id,
        })),
      [data]
    ) || [];

2:

  const list = useMemo(
    () =>
      data?.items?.map((i) => ({
        label: i.email as string,
        value: i.id,
      })) || [],
    [data]
  );

How should we useMemo in this case ?

1: when memo is undefined return [] 2: memoize undefined as []


Solution

  • If you use option 1 and data or data.items does not exist, then you will create a brand new empty array on every render. The fact that the array reference is changing can become a problem based on what you do with list. For example, if list is passed into a dependency array of another useMemo, you will break that memoization on every render.

    So if you need a stable array reference, you should use #2. The empty array will be created just once, the first time data or data.items does not exist, and then it will be reused (until data changes)

    If you don't need a stable array reference, then it doesn't make much difference for now. But at some point in the future you might add code that needs a stable reference, so i would do #2 anyway so you don't need to change it later.