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.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more