React 앱에서 서버 상태를 효율적으로 관리하고, 비동기 로직을 쉽게 다루게 다룰 수 있게 해주고
데이터 패칭 및 상태 관리 라이브러리로 서버에서 데이터를 가져오고 동기화하는 과정이 크게 단순화 된다.
📦설치 하기
먼저 React Query와 Devtools를 설치한다.
npm install @tanstack/react-query
npm install @tanstack/react-query-devtools
또는 yarn 사용 시,
yarn add @tanstack/react-query
yarn add @tanstack/react-query-devtools
📝 기본 사용법
1. App.tsx를 QueryClientProvider로 감싸기
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
const queryClient = new QueryClient();
const App = () => (
<QueryClientProvider client={queryClient}>
<YourAppRoutes />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
2.useQuery - 데이터 조회(GET)
const { data, isPending, isError } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
});
3. useMutation - 데이터 생성/수정/삭제
const mutation = useMutation({
mutationFn: createPost,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] });
}
});
💎 Life Cycle 상태
| 상태 | 설명 |
| fresh | 최신 상태(staleTime 동안 유지) |
| fetching | 데이터 요청 중인 상태 |
| stale | 만료 상태, 다시 요청될 수 있음 |
| inactive | 사용 중이 아닌 상태지만 캐시 유지 중 |
| delete | 캐시에서 제거됨 |
Query 옵션
React Query에서 자주 사용하는 useQuery 옵션들을 정리하면 다음과 같다.
| 옵션 | 설명 | 기본값 |
| queryKey | 캐시를 식별하는 유니크 키 | 필수 |
| queryFn | 데이터를 가져오는 함수 | 필수 |
| enabled | 쿼리 실행 여부 (false면 비활성화) | true |
| staleTime | fresh 상태 유지 시간(ms) | 0 |
| cacheTime / gcTime | inactive 상태 캐시 보존 시간(ms) | 300000 (5분) |
| refetchOnWindowFocus | 창 포커스 시 refetch | true |
| refetchOnReconnect | 네트워크 재연결 시 refetch | true |
| refetchOnMount | 마운트 시 refetch | 'always' |
| placeholderData | 데이터를 불러오기 전 보여줄 임시 데이터 | 없음 |
| select | 반환되는 데이터를 가공하여 리턴 | 없음 |
| retry | 실패 시 재시도 횟수 | 3 |
| retryDelay | 재시도 간격(ms 또는 함수) | 1000 |
| suspense | React Suspense 사용 여부 | false |
| useErrorBoundary | 에러를 ErrorBoundary로 전달 | false |
| meta | 쿼리마다 부가 정보 저장 가능 (예: error 메시지) | 없음 |
'FE > React' 카테고리의 다른 글
| 🌍 i18n이란? 프론트엔드 개발에서 국제화를 쉽게 이해하기 (0) | 2025.05.22 |
|---|---|
| React에서 function Page() : 함수 선언식(function declaration) vs const Page()=>{} 함수 표현식(function expresssion) 차이점 (0) | 2025.05.22 |
| @tanstack/react-table 개념과 사용법 완전 정리 (0) | 2025.05.18 |
| React와 Node.js (0) | 2025.05.14 |
| 상태 관리 라이브러리 : zustand 사용법 및 예제 (0) | 2025.05.12 |