React

[React] Tanstack Query 사용해 보기

woo.oing 2025. 10. 29. 18:39

아래 강의를 수강하며 배운 내용을 정리한 글입니다

[한 입 크기로 잘라먹는 실전 프로젝트 - SNS 편 - 이정환] https://inf.run/SbJ8w

 

 

가장 대표적인 서버 상태 관리 라이브러리인 Tanstack Query를 사용하여 프론트엔드에서 API 조회를 디테일하게 제어할 수 있습니다

기존에 react query라는 이름으로 알고 있었는데 리액트 뿐만 아니라 다른 프레임워크도 지원하게 되면서 tanstack query라는 이름으로 변경되었습니다

 

https://tanstack.com/query/latest

 

TanStack Query

Powerful asynchronous state management, server-state utilities and data fetching. Fetch, cache, update, and wrangle all forms of async data in your TS/JS, React, Vue, Solid, Svelte & Angular applications all without touching any "global state"

tanstack.com

 

 

1. 설치 및 설정

프로젝트 터미널에 아래 명령어를 입력하여 설치해주고 main.tsx 파일에 다음과 같은 설정 코드를 추가합니다

npm i @tanstack/react-query
npm i @tanstack/react-query-devtools // devtools 설치 시
const queryClient = new QueryClient();

createRoot(document.getElementById("root")!).render(
  <BrowserRouter>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </BrowserRouter>,
);

 

 

2. 사용해보기

useQuery를 호출하여 queryKey(필수값), queryFn, 기타 캐싱 조건들을 설정합니다 

  const { data, isLoading, error } = useQuery({
    queryFn: fetchTodos,
    queryKey: ["todos"],
  });

 

 

캐싱 메커니즘의 5가지 상태

- fetching: 데이터를 불러오는 중일 때

 

- fresh: 데이터가 최신 상태일때

fresh → staleTime (유통기한, 기본 0초) → stale

 

- stale: 데이터를 불러온지 시간이 지난 상태

stale → 리페칭 → fetching

 

리페칭 실행 조건

* 데이터가 이미 있으면 새로 불러오기 전까지는 이전 데이터를 보여줍니다

1. Mount: 데이터를 사용하는 컴포넌트가 마운트된 시점

2. WindowFocus: 탭에 다시 돌아온 시점

3. Reconnect: 인터넷이 다시 연결된 시점

4. Interval: 특정 시간 주기로 실행

 

- inactive: 해당 데이터를 사용하는 컴포넌트가 없을 때 (사용되지 않는 상태)

inactive → gcTime (기본 5분) → deleted

 

- deleted: 메모리에서 제거된 상태

 

 

공통으로 사용하게 될 글로벌 캐싱은 아래와 같이 작성하여 설정할 수 있습니다 

// main.tsx
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 0,
      gcTime: 5 * 60 * 1000,

      // retry: 0,
      refetchOnMount: true,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      refetchInterval: false,
    },
  },
});