@mnl@hachyderm.io

Prefetching Data on Hover with RTK Query

(this is another one of my articles written with heavy use of claude.ai/ChatGPT. I think it works quite well! Original prompt which then got fairly heavily edited and refined. I used claude because ChatGPT is down, which usually has a bit of trouble with newer technical content, but prompting it with the docs worked ok.)

RTK Query is a powerful tool for managing server state in Redux applications. It lets you define your API endpoints as simple objects inside the Redux store instead of making raw API calls in components.

For example, here is how we might define a categories API endpoint:

// apiSlice.js
import { createApi } from '@reduxjs/toolkit/query';

export const categoryApi = createApi({
  reducerPath: 'categoryApi',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://example.com/api/', 
  }),
  endpoints: builder => ({
    getCategory: builder.query({
      query: url => `category/${url}`
    }),
  })
})

// Provide auto-generated React hooks for each endpoint
export const {
  useGetCategoryQuery,
  usePrefetch
} = categoryApi;

By defining endpoints like getCategories, RTK Query generates React hooks like useGetCategoryQuery that components can use to fetch data. It handles all the underlying logic for caching, request deduplication, polling, and more. Multiple components can share the same cached data using these auto-generated hooks.

Prefetching with the usePrefetch Hook

One useful feature of RTK Query is the ability to prefetch data before a component needs it. This avoids delays when a user navigates to a new screen. RTK Query offers a usePrefetch hook that returns a function triggering the actual request, which leads to a cache update.

For an ecommerce site, prefetching category data on hover is useful to accelerate product browsing. When the user hovers over a category, we can fetch that category's products in the background.

Here is how we might prefetch a category and its products:

const prefetchCategory = usePrefetch('getCategory');
const prefetchProducts = usePrefetch('getProducts');

return (
  <Link 
    to={`/categories/${category.id}`}
    onMouseEnter={() => {
      prefetchCategory(category.id);
      prefetchProducts({ categoryId: category.id });
    }}>
    {category.name} 
  </Link>
);

Now when hovering over a category, the category details and products are fetched in anticipation of navigation. This powers a smooth browsing experience.

The same approach could be used for individual products, search suggestions, and any other data that can be preemptively cached. RTK Query handles all the underlying data subscriptions, caching, and request deduplication automatically.