React-query problem: I fetched a list and I want to avoid needlessly refetching the same data on my detail page.
Solution: Use setQueryData to pre-populate the detail page cache. Now the detail page loads immediately. 🔥
Example below: This fetches a list of users, then stores each of the user's details in react-query's cache so that the fetch on the details page automatically has a cache hit.
Note: This pattern only works if the list page fetches the same properties as the detail page.⚠️
Before creating a custom hook, I search the web. Often, an open source custom hook already exists.
A few favorites:
useDebounce
useLocalStorage
useIntersectionObserver
Many more here: https://t.co/SjjBZiVDRC
One of my favorite React Hook Form features:
I can use a Zod schema to configure form validation with a single line of code.
See the highlighted line below.
Slick. 🔥
Problem: Cache invalidation is hard.
Example: One of my clients uses React Query heavily. We have 100's of query keys, and many are quite complex. When a mutation occurs, we often need to invalidate multiple related queries. So, it's easy to forget to invalidate related queries when a mutation occurs.
Solution: Colocate related queries in the same file and centralize keys at the top. This helps us reuse keys, and helps us find related queries when writing a new mutation. (Example below)
Anyone else have tips in this area? cc @TkDodo
Problem: You want to know how much of your TypeScript code is type safe.
Solution: type-coverage
This CLI tool reports the percentage of your code that’s type safe.
It reports usage of:
🚩 any
🚩 as assertions (foo as string)
🚩 type assertions (<string>foo)
🚩 Non-null assertions (foo!)
🚩 Use of plain Object type (Object or {})
And it provides a detailed report of all the spots you should consider changing to improve type safety.
Related: Use typescript-coverage-report to get a nice visual output like this:
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. 👍