Introducing React Query at Work

Our service previously managed client state with MobX and server state with try/catch. While revamping the search page, we felt the need for a new way to manage server state and introduced React Query.

  1. Fetching happened multiple times after the initial fetch.
  2. Was there a useful library for handling infinite scrolling?
  3. We needed to manage loading and error states.
  4. We needed caching to improve search page performance.

After identifying these issues, we decided to use React Query’s caching for efficient fetching, useInfiniteScroll to handle infinite scrolling, and variables provided by React Query, such as isLoading, to display skeleton UI.


People unfamiliar with server state management tend to have this question.

Why manage client and server state separately?

There are five main reasons.

1. Separation of Concerns
Server state is managed on the server, which sends only the data the client needs. This includes retrieving data from databases, executing business logic, and checking permissions.
Client state relates to the user interface, including user input, UI component state, and temporary data.
This separation makes the codebase easier to understand and maintain.

2. Data Consistency
The server is the authoritative source of data, providing consistent data to every client.
Clients manage state based on the latest data received from the server.
This ensures consistency and reduces synchronization issues.

3. Performance Optimization
Sending server state to the client only when needed reduces network usage.
Clients can request only the data they need and avoid unnecessary transfers.
Managing client state locally improves UI responsiveness.

4. Scalability
A server can efficiently manage state for multiple clients.
Client state is managed locally for each user, reducing server load.
This structure allows the application to scale to more users and requests.

5. Maintainability and Extensibility
Separating client and server code lets each part be updated and extended independently.
Adding features and fixing bugs becomes easier.

After actually separating server and client state, our work became more efficient, and server state became much easier to handle.


Useful terminology

  1. Query: the useQuery hook, an API endpoint, a remote data source.
  2. Mutation: the useMutation hook; a request to add new data or modify existing data.
  3. Query caching: storing query results in memory.
  4. Query invalidation: the process of invalidating a query or marking it as stale.

Query keys matter in React Query

Their purposes:

Cache keys: query results are cached automatically under the corresponding key. The same query key uses a previously cached result.

—> Prevents duplicate requests and improves performance.

Dependency management: detects changes in dependent data and reruns the query when that data changes. —> Maintains data consistency.

However, every variable that changes must be included.

function Todos({ todoId }) {
	const result = useQuery({
		queryKey: ["todos", todoId],
		queryFn: () => fetchTodoById(todoId),
	});
}

Using React Query in different situations

1. Implementing infinite scrolling with useInfinite scroll

	const [originData, setOriginData] = useState([])
	const [pageParam, setPageParam] = useState(0)
	const [initialPage, setInitialPage] = useState(0)
	const limit = 10
	const {data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading} = useInfiniteQuery(
		['posts'],
		async ({pageParam = initialPage}) => {
			setPageParam(pageParam)
			const response = await fetchPosts(pageParam, limit);
			return response;
		},
		{

			getNextPageParam: (lastPage) => lastPage.products.pagination.offset + limit,
			onSuccess: (data) => {
				setOriginData((prev) => [...prev, ...data.pages[pageParam / limit].products.products])
			}
		}
	);

While connecting this, I ran into an issue where all fetched data reset when navigating back. Suspecting caching, I added caching options, but the result was the same. The cause was that I needed to use the data returned by React Query directly. Assigning the data to useState causes problems when useState resets, making it difficult to use caching properly.


2. How do you use useQuery when a button is clicked?

Originally:

const data = useQuery({
	queryKey: ["dataItems"],
	queryFn: () => getDataItems(id),
});
let resultStr = "";
if (data.data) {
	data.data.map((item) => {
		resultStr += item.data_value;
	});
}

Trial and error:

The action runs four times after fetchtitle.
With React Query, fetching happens only once even if the page renders multiple times.
Putting the action in onSuccess also makes it run only once.
  1. fetch title
  2. Save command
  3. PDF command
  4. 559-969
  5. Performance measurements needed
  6. Server cost issue
  7. Next auto save function

React Query and SSR — Understanding It Through the Library’s Code

Wondering whether setuphandlers needs changing.

4. useQueries when the same query needs to run multiple times

5. mutateAsync when an asynchronous request is needed

Deciding on a React Query hierarchy

Managing query keys

The unique key you provide is used internally for refetching, caching, and sharing your queries throughout your application.

It is used for refetching, caching, and calls from elsewhere.

const queryKey = ["userData", userId];

SSR and React Query

There are two ways to use React Query in server-side props.

  1. Use initialData.
    1. It is simple to use, but inefficiently requires passing data through props to the client-side component that uses it.
  2. Dehydrate the cache on the server and hydrate it on the client.

Dehydrating the cache on the server means restoring or reusing cached data before sending data from a server-side rendered page to the client.

More specifically, server-side rendering fetches the page’s data on the server, renders it as HTML, and sends it to the client. The client can cache data it has already requested or parts of a page.

Cached data helps load pages faster and improve performance by avoiding new requests during navigation.

So “dehydrating the cache on the server” means that, when fetched data is stored in the cache, the server restores and uses that cached data before sending it to the client. This lets the client load pages faster and improves the user experience.

To “hydrate” on the client means combining server-rendered HTML content with client-side JavaScript to make an interactive web page. This generally applies to pages rendered through SSR or static generation.

More specifically, client-side hydration refers to this process:

  1. Receive server-rendered HTML: the server sends the HTML resulting from the page’s initial rendering to the client.
  2. Combine it with JavaScript: client-side JavaScript combines with the page’s HTML to handle interactivity and dynamic behavior.
  3. Add event handling and interactions: client-side JavaScript sets up event handlers and interactive elements, preparing the page to update or change in response to user actions.

This process efficiently combines client-side JavaScript with the initial HTML sent by the server, letting users load and interact with pages quickly. Hydration helps optimize initial page loading and improve the user experience.

Takeaway: when fetching data server-side, cached data can be retrieved faster.

Refetch options

When refetching is not important:

const DISABLED_REFETCH_OPTIONS :{
readonly refetchOnWindowFocus : false;
readonly refetchInterval: false ;
readonly refetchOnMount: false;
readonly refetchOnReconnect: false;
readonly refetchIntervalInBackground: false
}

staleTime and cacheTime

  1. cacheTime counts down when a query is inactive, while staleTime counts down when it is active.

Suspense option

Things to watch out for

Be careful with user-related information.

Information visible only to user a must not be shown to user b.

For performance reasons, Next.js recommends page generation in the order SSG -> ISR -> SSR.

Errors I encountered when starting out

onSuccess does not run when cached data is used.

If something seems wrong with caching, the query key may be incorrect.

Without setting retry to 0, errors cause endless requests.

When using it as a hook, handle it asynchronously with async

useMutateAsync

Try useQueries when the same query needs to run twice

Most of this knowledge came from the docs.

React Query makes things easy for beginners to understand…

But what should I do with this?

Let’s think about it.

Hmm.

What’s the Difference Between isLoading and isFetching in React Query?

The frustrating isLoading and isFetching.

Going forward…

I need to think about query keys, folder structure, and how to separate data logic. Retrospective on Introducing React Query at Work, Part 2

refetch

[Next.js] Implementing SSR with React Query

https://github.com/mingdolacucudas/reactquery-searching/blob/main/src/App.js

React Query in an SSR Environment

Code refactoring