DEV Community

loading...

Discussion on: Don't over useState

Collapse
tkdodo profile image
Dominik D Author

I don’t see why - quite the opposite actually.
Before: initial render - fetch effect does setState, triggers render - effect that syncs data runs, triggers render. That’s 3 renders. In the final version, it’s just 2 renders: initial render + render from the one setState in the effect.

I didn’t mention this in the article because it shouldn’t be an argument though. The amount of renders usually doesn’t matter because renders are very fast. If they are not, try to make them fast rather than minimizing the amount of re-renders :)

Collapse
tkdodo profile image
Dominik D Author

What we do is calling computeCategories in every render, which we didn’t do before. This doesn’t matter unless this function is expensive. If we have proof that we need to optimize it, we can do:

const categories = React.useMemo(
  () => data ? computeCategories(data) : [],
  [data]
)
Enter fullscreen mode Exit fullscreen mode

and now we call that function the same amount of times as before.