Best Practice for Cache Keys #1437
Unanswered
danielstreit
asked this question in
General
Replies: 1 comment 1 reply
-
You can still use external functions like you have, but you’ll just need to change the call signature of those functions to use the new query context object instead of the args your used to. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm curious about this change: https://react-query.tanstack.com/guides/migrating-to-react-query-3#query-key-partspieces-are-no-longer-automatically-spread-to-the-query-function.
Previously, we were using the cache keys to pass the url and params to our fetch function. This ensured a 1:1 relationship between the request and the data we got back. If the url or params changed, it would be a different request and a different cache key. If someone made the same request in a different part of the app to the same endpoint, it just worked. They didn't need to think about whether that request was made somewhere else as well.
In the upgrade to v3, this pattern is still possible, but it looks like it is no longer recommended. Instead, "Inline functions are now the suggested way of passing parameters to your query functions". This breaks the relationship between the cache key and the actual fetch request. How do you ensure that the cache key is consistent across an app? Are there any suggested patterns for this?
In our first uses, we did use a style similar to the new suggestion. But, what we had found when we had no code-enforced relationship between the fetch and the cache key is that cache keys would drift. We'd have cache misses when we should have hit. We didn't get to the point were we had incorrect hits, but I feared it.
Another approach we tried was exporting cache key generators with our fetch functions. For example,
fetchPost
would have a method on it likefetchPost.makeCacheKey
. This works, but creates a lot of boilerplate and still doesn't enforce the connection between the cache key and fetch function with code; it is only a convention.Anyway, I realize this is a long winded question and we can still use the
context
to do what we were doing, but I'm curious if there are better alternatives or suggestions around defining cache keys so that they are consistent across a large app.Thanks!
Beta Was this translation helpful? Give feedback.
All reactions