Hacker News new | ask | show | jobs
by fabian2k 976 days ago
There have been endless discussions about state management in React. React Query solved the most common and most annoying part of state management for me, which was everything that you fetched via the network. The part that remains is straightforward enough with the built-in useState/useReducer.

It does take a moment to learn React Query. You should make sure everyone understands how query keys work and uses them correctly. I saw some confusion there when we started using it, and one developer trying to work around stuff manually that React Query does automatically if you properly set up your query keys and invalidate them.

1 comments

Can you provide examples regarding right/wrong common mistakes you found in use?
It was more of a general misunderstanding on how React Query is supposed to work, partially triggered by some mistakes in defining the query keys that meant that React Query didn't work as intended.

I'd recommend this blog post (or actually all blog posts on React query on that site):

https://tkdodo.eu/blog/effective-react-query-keys

What I observed was that the query keys were not consistently defined, which broke automatic refetching when the data was modified and invalidated. So the developer added some manual refetches because they thought React Query couldn't handle that automatically.

You need a consistent structure for your query keys and use that everywhere. Then you only need to make sure to invalidate the correct part of the query key hierarchy and the rest works automatically.

First: Realize that React Query isn't a library for fetching data, but a library for caching the fetched data. So think about how you will be invalidating that cache. For us, the rule of thumb was that each fetch to the API should have it's own cache key in React Query.

Second: The data in cached in React Query is effectively globally available, so it comes with all the benefits and pitfalls that globals have. We use Storybook and do not use React Query in the components that have stories, so React Query is only used in the root components of the app.

ReactQuery state is not global. It's set in a context, and it takes two lines to write a Storybook decorator that ensures a unique cache for each story.

It may still make sense to keep react-query out of your storybooks though.