Problem: With react-query, we may declare inconsistent query keys


Problem:
With react-query, we may declare inconsistent query keys. That leads to cache misses and duplicated cache entries. πŸ‘Ž

Solution:
1. Wrap each useQuery call in a custom hook. Store the hooks in /hooks.

2. Put the fetch call in the custom hook. *Don’t export it*.

3. Forbid calling useQuery outside /hooks via ESLint’s no-restricted-imports. Forbid calling fetch outside /hooks too.

This assures the hook is the only way to query. πŸ‘

The custom hook also makes each call site simpler. No more repeated config.

Each query is one line of code. πŸ‘

Oh, and if you're calling an API that uses OpenAPI, you can generate react-query wrappers automatically using Orval. πŸ”₯

https://orval.dev/guides/react-query
And if you want to take this a step farther, you can centralize query keys via a query key factory.

More here: https://tkdodo.eu/blog/effective-react-query-keys#use-query-key-factories

And here: https://tanstack.com/query/v4/docs/react/community/lukemorales-query-key-factory

I used fetch in the example, but I prefer Ky in real apps.

https://github.com/sindresorhus/ky
Some people asked for the ESLint config required to make this happen.

Here ya go.

This only allows use of useQuery under src/hooks.

It throws a helpful error message when someone calls useQuery outside the /hooks folder.

See the alt for the raw code.

View original on X