DEV Community

Discussion on: You (probably) don't need that useState + useEffect

Collapse
 
_faridjunior profile image
mohamed farid

Thanks for this article

for me, the first approach is easier to reason about,
you see that items subscribe to changes of data,
but In the second approach, you can get messy
about why items are changing or when,
for the first approach using useMemo and
extracting logic to separate functions will make it better.

useMemo(() => {
    setItems(getItems(data));
    setItemsLength(getItemsLength(data));
  }, [data, setItems, setItemsLength]);

const getItems = (data) => {
  // I always like to protect against bad/unexpected data
  if (!data || !data.items) return [];

  return data.items;
};

const getItemsLength = (data) => {
  return getItems(data).length;
};

Enter fullscreen mode Exit fullscreen mode
Collapse
 
townofdon profile image
Don Juan Javier

Thanks for the feedback. I'm not following how adding additional state and memoization helps to reason about the data. For me, simple data derivation is much easier to reason about, especially since there is less state being managed. As an app scales it especially becomes important to try and reduce complexity wherever possible.