Sitemap
bytePudding

bytePudding

Learning TECH !

Tanstack Query

--

React Query (TanStack Query) 개념

핵심 아이디어

React Query는 “서버 상태”를 관리하는 라이브러리입니다.

useState/useReducer  →  클라이언트 상태 (UI, 폼 등)
React Query → 서버 상태 (API 데이터)

직접 훅을 만들 때 고민했던 것들을 알아서 처리해줍니다:

  • 로딩/에러 상태
  • 중복 요청 방지
  • 캐싱 (같은 요청은 다시 안 함)
  • 자동 재시도
  • 데이터 최신화

설치

npm install @tanstack/react-query

1단계: 최상단에 Provider 설정

frontend/src/main.tsx 또는 App.tsx:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();function App() {
return (
<QueryClientProvider client={queryClient}>
<Router />
</QueryClientProvider>
);
}

Get bytePudding’s stories in your inbox

Join Medium for free to get updates from this writer.

2단계: useQuery — 데이터 가져오기 (GET 개념)

import { useQuery } from '@tanstack/react-query';
import { fetchRetrieveData } from '../actions/fetchRetrieveData';
function WordList() {
const { data, error, isPending } = useQuery({
queryKey: ['words'], // 캐시 키 (배열)
queryFn: () => fetchRetrieveData('/words', {}),
});
if (isPending) return <div>로딩중...</div>;
if (error) return <div>에러 발생</div>;
return <div>{data}</div>;
}

queryKey가 핵심입니다. 같은 키면 캐시된 데이터를 씁니다:

queryKey: ['words']                  // words 전체
queryKey: ['words', userId] // userId별로 따로 캐시
queryKey: ['words', { page: 1 }] // 파라미터 포함

3단계: useMutation — 데이터 변경 (POST/PUT/DELETE 개념)

import { useMutation, useQueryClient } from '@tanstack/react-query';
function AddWord() {
const queryClient = useQueryClient();
const { mutate, isPending } = useMutation({
mutationFn: (newWord: string) =>
fetchRetrieveData('/words/add', { word: newWord }),
onSuccess: () => {
// 성공하면 words 캐시를 무효화 → 자동으로 재조회
queryClient.invalidateQueries({ queryKey: ['words'] });
},
});
return (
<button onClick={() => mutate('apple')} disabled={isPending}>
단어 추가
</button>
);
}

useQuery vs useMutation 구분

useQueryuseMutation목적데이터 조회데이터 변경실행 시점컴포넌트 마운트 시 자동mutate() 호출 시해당 HTTPGET (또는 조회용 POST)POST / PUT / DELETE

현재 프로젝트에 적용한다면

지금 만들던 useRetrieveData 훅을 대체하면:

// Before — 직접 만든 훅
const { data, error, isPending } = useRetrieveData('/words', { userId: 1 });
// After — React Query
const { data, error, isPending } = useQuery({
queryKey: ['words', userId],
queryFn: () => fetchRetrieveData('/words', { userId }),
});

fetchRetrieveData 액션 함수는 그대로 재사용할 수 있어서 actions 폴더 구조도 살아있습니다.

--

--