DEV Community

Shin-Young Jung
Shin-Young Jung

Posted on

Improving UX by using cache

Problem

Let's say that there are two buttons. When users click each button, the button leads users to "page1" and "page2".

While switching from one page to another, there are some loading state that waiting for the API responses. This may make users feel that the service is not fast enough and buggy.

If there are data that we can use to preload while fetching new data from the server, users may think that the service is very responsive and fast.

Tanstack Query

Tanstack Query (a.k.a. React Query) provides many productive functions including cache management. When we use useQuery function to fetch API, it store the cache and use it when users come back to the page, and refresh the data asynchronously. Thus, if we don't want users to wait for the new data while switching pages, somehow data should be cached before switch pages.

Prefetch data

Tanstack Query provides the function called prefetchQuery, and we can use this to pre-cache the data. This is how we can use it.

// The results of this query will be cached like a normal query
queryClient.prefetchQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  })
Enter fullscreen mode Exit fullscreen mode

Please note that the queryKey should be the same as what actual API fetch will use in useQuery.

This is great! However, because we prefetch all the data that may not be reached by users (Users may see the single page and leave the service), the service may do over fetch the data from the server. Thus, when we use the prefetchQuery, please consider what's the better options, overfetch or waiting for the page update.

Top comments (0)