0% completed
Query keys are fundamental to how React Query identifies, caches, and updates your data. A well-defined query key strategy ensures efficient caching, granular control over data updates, and prevents unnecessary re-fetches.
A query key is essentially a unique identifier for your data within React Query's cache. Think of it as the primary key in a database table. It's crucial to choose query keys that:
Lets look at an example of fetching a single post from an API.
// Fetching a single post useQuery(['post', postId], () => fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`).then(res => res.json()) )
In this example, ['post', postId] becomes the query key. It clearly indicates that we're fetching a single post with a specific ID. If postId changes, React Query recognizes it as a new query and fetches the corresponding data.
Caching in the context of API data involves storing the data received from an API locally, so that future requests for the same data can be served from the cache rather than making repeated network requests. This improves performance, reduces server load, and minimizes latency by quickly delivering the data without needing to fetch it from the remote API every time.
Cached data usually has a time limit, ensuring it stays current. By default, React Query caches data for 5 minutes. Here are some key options:
staleTime: (default: 0) - How long (in milliseconds) fetched data is considered fresh. Data is only refetched if it becomes stale.
cacheTime: (default: 5 minutes) - How long (in milliseconds) data remains in the cache, even if inactive.
refetchOnWindowFocus: (default: true) - Automatically refetches data when the browser window regains focus.
refetchOnInterval: (default: false) - Refetches data at a specified interval (in milliseconds).
You can customize this:
// Fetch posts but keep them cached for 10 minutes, even if inactive useQuery('posts', fetchPosts, { cacheTime: 10 * 60 * 1000 // 10 minutes });
In this example, we set the caching time to 10 minutes.
While automatic caching is great, sometimes you need manual control:
queryClient.invalidateQueries('key'): Removes data from the cache, forcing a refetch on the next render where the query is active. Useful after mutations to refresh data.
queryClient.setQueryData('key', newData): Directly updates the cache with new data. Use with caution, usually in conjunction with optimistic updates.
By mastering query keys and cache management techniques, you can optimize your React Query implementation, reduce unnecessary data fetching, and provide a smoother user experience.
.....
.....
.....