tanstack query
useQuery
- isPending
- error
- data
- isSuccess
1. Getting started
Overview
TanStack Query (formerly known as React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.
React Query is compatible with React v18+ and works with ReactDOM and React Native.
설치
npm i @tanstack/react-query
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
const queryClient = new QueryClient()
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
)
}
function Example() {
const { isPending, error, data } = useQuery({
queryKey: ['repoData'],
queryFn: () =>
fetch('https://api.github.com/repos/TanStack/query').then((res) =>
res.json(),
),
})
if (isPending) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
<strong>👀 {data.subscribers_count}</strong>{' '}
<strong>✨ {data.stargazers_count}</strong>{' '}
<strong>🍴 {data.forks_count}</strong>
</div>
)
}
TypeScript
함수에 리턴타입 명시하기
This works best if your queryFn has a well-defined returned type. Keep in mind that most data fetching libraries return any per default, so make sure to extract it to a properly typed function:
const fetchGroups = (): Promise<Group[]> =>
axios.get('/groups').then((response) => response.data)
const { data } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const data: Group[] | undefined
type 좁히기
const { data, isSuccess } = useQuery({
queryKey: ['test'],
queryFn: () => Promise.resolve(5),
})
if (isSuccess) {
data
// ^? const data: number
}
에러타입 정의가능
If you want to throw a custom error, or something that isn't an Error at all, you can specify the type of the error field:
const { error } = useQuery<Group[], string>(['groups'], fetchGroups)
// ^? const error: string | null
error field type speicifc
import axios from 'axios'
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: Error | null
if (axios.isAxiosError(error)) {
error
// ^? const error: AxiosError
}
전역에러 등록하기
v5 부터 지원
import '@tanstack/react-query'
declare module '@tanstack/react-query' {
interface Register {
defaultError: AxiosError
}
}
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: AxiosError | null
전역 meta data
import '@tanstack/react-query'
interface MyMeta extends Record<string, unknown> {
// Your meta type definition.
}
declare module '@tanstack/react-query' {
interface Register {
queryMeta: MyMeta
mutationMeta: MyMeta
}
}
query, mutation key 등록
import '@tanstack/react-query'
type QueryKey = ['dashboard' | 'marketing', ...ReadonlyArray<unknown>]
declare module '@tanstack/react-query' {
interface Register {
queryKey: QueryKey
mutationKey: QueryKey
}
}
쿼리옵션 타이핑
import { queryOptions } from '@tanstack/react-query'
function groupOptions() {
return queryOptions({
queryKey: ['groups'],
queryFn: fetchGroups,
staleTime: 5 * 1000,
})
}
useQuery(groupOptions())
queryClient.prefetchQuery(groupOptions())
쿼리옵션이 없으면 generic 을 넘겨주지 않으면 data 의 타입이 unknown 이 될 것이다.
const data = queryClient.getQueryData<Group[]>(['groups'])
shadcn
zod
zustand
react query
react form hook
'Frontend > 스터디' 카테고리의 다른 글
테일윈드 CSS (1) | 2025.05.29 |
---|---|
한 번에 끝내는 Node.js 웹 프로그래밍 초격차 패키지 Online FE (2) | 2025.05.21 |
리액트 독학 (0) | 2022.10.04 |
한 번에 끝내는 Node.js 웹 프로그래밍 초격차 패키지 Online (1) | 2022.09.23 |
HTML&CSS boost course (0) | 2022.03.10 |