리액트 쿼리란?
it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.
현재 TanStack Query라는 명칭으로 변경되었으며 v5버젼까지 업데이트 되었다.
매번 업데이트마다 자주 변경되니 공식문서를 자주 참고하면 좋다.
$ npm i @tanstack/react-query
# or
$ pnpm add @tanstack/react-query
# or
$ yarn add @tanstack/react-query
QueryClient가 인스턴스를 생성, QueryClientProvider를 통해 앱 전체에서 생성한 QueryClient에 접근 가능하도록 해준다.
import {
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
import { getTodos, postTodo } from '../my-api'
// Create a client
const queryClient = new QueryClient()
function App() {
return (
// Provide the client to your App
<QueryClientProvider client={queryClient}>
<Todos />
</QueryClientProvider>
)
}
데이터 fetching시 사용
queryKey
v4 이후로는 배열로 선언, 쿼리의 고유 키 애플리케이션 전체에서 쿼리를 다시 가져오고, 캐싱하고, 공유하는 데 내부적으로 사용됩니다.
queryFn
data fetching 하는 함수
status
isPending: 쿼리에 아직 데이터가 없습니다.
isError: 쿼리에 오류가 발생했습니다.
isSuccess: 쿼리가 성공했고 데이터를 사용할 수 있습니다.
import { useQuery } from '@tanstack/react-query'
function Todos() {
const { isPending, isError, data, error } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodoList,
})
if (isPending) {
return <span>Loading...</span>
}
if (isError) {
return <span>Error: {error.message}</span>
}
// We can assume by this point that `isSuccess === true`
return (
<ul>
{data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
서버의 데이터를 변경할 때 사용 HTTP POST, PUT, DELETE 요청 가능.
import { useMutation } from '@tanstack/react-query'
const mutation = useMutation({
mutationFn: postTodo,
onSuccess: () => {
console.log('Success')
onError: () => { console.error('Error') },
onSettled: () => { console.log('Settled') } //결과와 상관없이 실행
},
})
$ npm i @tanstack/react-query-devtools
# or
$ pnpm add @tanstack/react-query-devtools
# or
$ yarn add @tanstack/react-query-devtools
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* The rest of your application */}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
https://tanstack.com/query/latest
https://github.com/ssi02014/react-query-tutorial