🔥 사용해 보기
233자
3분
이 섹션에서는 React Query의 세 가지 핵심 개념을 간단히 소개합니다. 이 개념들을 이해하면 React Query를 효과적으로 사용할 수 있습니다.
이 세 가지 개념은 React Query의 핵심 기능을 구성합니다. 이어지는 문서에서 각 개념을 자세히 살펴볼 것입니다.
실제로 동작하는 예제를 보고 싶다면, 간단한 StackBlitz 예제를 확인해보세요.
다음은 React Query의 기본적인 사용법을 보여주는 코드 예제입니다:
typescript
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// 클라이언트 생성
const queryClient = new QueryClient()
function App() {
return (
// 앱에 클라이언트 제공
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
function Todos() {
// 클라이언트 접근
const queryClient = useQueryClient()
// 쿼리
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
// 변이
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
// 무효화 및 다시 가져오기
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
<div>
<ul>{query.data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
<button
onClick={() => {
mutation.mutate({
id: Date.now(),
title: '빨래하기',
})
}}
>
할 일 추가
</button>
</div>
)
}
render(<App />, document.getElementById('root'))
typescript
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// 클라이언트 생성
const queryClient = new QueryClient()
function App() {
return (
// 앱에 클라이언트 제공
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
function Todos() {
// 클라이언트 접근
const queryClient = useQueryClient()
// 쿼리
const query = useQuery({ queryKey: ['todos'], queryFn: getTodos })
// 변이
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
// 무효화 및 다시 가져오기
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
<div>
<ul>{query.data?.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
<button
onClick={() => {
mutation.mutate({
id: Date.now(),
title: '빨래하기',
})
}}
>
할 일 추가
</button>
</div>
)
}
render(<App />, document.getElementById('root'))
이 코드는 React Query를 사용하여 할 일 목록을 관리하는 간단한 애플리케이션을 구현합니다. useQuery를 사용해 할 일 목록을 가져오고, useMutation을 사용해 새로운 할 일을 추가합니다. 새 할 일을 추가한 후에는 invalidateQueries를 호출하여 할 일 목록을 다시 가져옵니다.
이 예제를 통해 React Query의 기본적인 사용법을 익힐 수 있습니다. 앞으로의 문서에서는 각 개념에 대해 더 자세히 다룰 것입니다.









