๐ŸŒ Web Development

TanStack Query

TanStack Query

A server state management library. Automates caching, synchronization, and updates.

๐Ÿ“– Detailed Explanation

TanStack Query (formerly React Query) is a powerful asynchronous data-fetching library for managing server state. It handles complex data synchronization logic such as caching, background updates, request deduplication, and optimistic updates declaratively.

The core concepts are Query (read) and Mutation (write). useQuery is used for GET requests, and useMutation for POST/PUT/DELETE requests. The queryKey identifies the cache, and staleTime and cacheTime give fine-grained control over the caching strategy.

TanStack Query supports various frameworks such as React, Vue, Solid, and Svelte. DevTools lets you inspect the cache state visually, which makes debugging easier, and its type inference with TypeScript is also excellent.

Compared with SWR, TanStack Query offers more features. It can handle complex scenarios such as Infinite Query, Prefetching, Placeholder Data, and Query Invalidation, making it well suited to large-scale applications.

๐Ÿ’ป Code Example

import {
  useQuery,
  useMutation,
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

// Provider ์„ค์ •
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5๋ถ„๊ฐ„ fresh
      retry: 3,
      refetchOnWindowFocus: true,
    },
  },
});

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyApp />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

// ๊ธฐ๋ณธ Query
function TodoList() {
  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['todos'],
    queryFn: () => fetch('/api/todos').then(r => r.json()),
    staleTime: 1000 * 60, // 1๋ถ„
  });

  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;

  return (
    <ul>
      {data.map(todo => <TodoItem key={todo.id} {...todo} />)}
    </ul>
  );
}

// Mutation๊ณผ ์บ์‹œ ๋ฌดํšจํ™”
function CreateTodo() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: (newTodo: { title: string }) =>
      fetch('/api/todos', {
        method: 'POST',
        body: JSON.stringify(newTodo),
      }).then(r => r.json()),

    // ๋‚™๊ด€์  ์—…๋ฐ์ดํŠธ
    onMutate: async (newTodo) => {
      await queryClient.cancelQueries({ queryKey: ['todos'] });
      const previousTodos = queryClient.getQueryData(['todos']);

      queryClient.setQueryData(['todos'], (old: Todo[]) => [
        ...old,
        { id: Date.now(), ...newTodo, completed: false }
      ]);

      return { previousTodos };
    },

    onError: (err, newTodo, context) => {
      queryClient.setQueryData(['todos'], context?.previousTodos);
    },

    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });

  return (
    <button
      onClick={() => mutation.mutate({ title: '์ƒˆ ํ• ์ผ' })}
      disabled={mutation.isPending}
    >
      {mutation.isPending ? '์ถ”๊ฐ€ ์ค‘...' : '์ถ”๊ฐ€'}
    </button>
  );
}

// ๋ฌดํ•œ ์Šคํฌ๋กค (Infinite Query)
function InfinitePostList() {
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery({
    queryKey: ['posts'],
    queryFn: ({ pageParam = 0 }) =>
      fetch(`/api/posts?cursor=${pageParam}`).then(r => r.json()),
    getNextPageParam: (lastPage) => lastPage.nextCursor,
  });

  return (
    <div>
      {data?.pages.map((page, i) => (
        <React.Fragment key={i}>
          {page.posts.map(post => <Post key={post.id} {...post} />)}
        </React.Fragment>
      ))}
      <button onClick={() => fetchNextPage()} disabled={!hasNextPage}>
        {isFetchingNextPage ? '๋กœ๋”ฉ...' : '๋” ๋ณด๊ธฐ'}
      </button>
    </div>
  );
}

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

In a technical meeting:

"Managing server data with global state is a synchronization nightmare. With TanStack Query, caching, refetching, and loading states are all handled for you, and you can check the cache right away in DevTools."

In a technical interview:

"What's the difference between staleTime and cacheTime?" - "staleTime is the time during which data is considered fresh, and cacheTime is the time an inactive query is kept in memory. If the data is stale, a background refetch occurs."

In a code review:

"You're not invalidating the related queries after the mutation succeeds. You need to refresh the list with invalidateQueries so the added item shows up right away. Or update the cache directly with setQueryData."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Cautions

๐Ÿ”— Related Terms

SWR React Suspense REST API Redux

๐Ÿ“š Learn More

๐Ÿ“„ TanStack Query Official Documentation ๐Ÿ“„ TanStack Query - Mutations Guide ๐Ÿ“„ TanStack Query - Optimistic Updates