-
When working with React Query, it's a good practice to avoid hardcoding cache keys within the useQuery hook. Hardcoded cache keys can lead to issues such as cache misses, stale data, and difficulty in maintaining and refactoring the codebase. To address this concern, I propose adding a new ESLint rule that will enforce the use of externalized cache keys. By externalizing the cache keys, developers can easily maintain and update them across the application without the risk of breaking existing cache behavior. Here's an example of how the rule would work:
const query = useQuery({
queryKey: ["user", "me"],
queryFn: getCurrentUser
});
export const currentUserQueryKey = ["user", "me"];
const query = useQuery({
queryKey: currentUserQueryKey,
queryFn: getCurrentUser
}); Why?imaging this scenario: a developer wants to invalidate the queryClient.invalidateQueries(["user", "me"]); and another developer update the query key to this const query = useQuery({
queryKey: ["users", "me"], // user => users
queryFn: getCurrentUser
}); Now the How to fix this? We define the query like this export const currentUserQueryKey = ["user", "me"];
const query = useQuery({
queryKey: currentUserQueryKey,
queryFn: getCurrentUser
}); and invalidate query like this queryClient.invalidateQueries(currentUserQueryKey); for more complex scenarios, like if you need the userId in your cache key, this article provided a very good solution Use Query Key factories |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
there is no difference between the "good" and "bad" example you're giving. Extracting something to a local const doesn't make anything better. This is not something we're going to enforce with eslint. |
Beta Was this translation helpful? Give feedback.
sure, but just because you export a constant called
currentUserQueryKey
also doesn't guarantee that it will be used everywhere. Nothing is stopping you from callingqueryClient.invalidateQueries(['foo', 'bar'])
and then have you wondering why the users aren't invalidated after that call. This is nothing a lint rule can solve. Libraries built on top of react-query, liketrpc
orzodios
on the other hand, can solve and have solved this problem.