React Query는 React Application에서 서버 상태를 불러오고, 캐싱하며, 지속적으로 동기화하고 업데이트하는 작업을 도와주는 비동기 상태 관리 라이브러리이다.
리액트에서 상태 관리를 위한 라이브러리는 redux, recoil 같은 라이브러리 등 다양하다.
대부분 이러한 상태 관리 라이브러리를 사용하며 클라이언트 상태와 서버 상태를 함께 담아두고 있는 경우가 대부분이다.
react-query를 사용해 서버 상태를 관리한다면 클라이언트 상태를 분리하여 관리할 수 있기 때문에 직관적이고 효율적인 관리가 가능해진다. 이 외에도 react-query에서 지원하는 다양한 옵션들을 사용해 캐싱, 에러처리, suspense, refresh, data fetching 조건 설정 등 기존에 불편하게 느꼈던 부분들을 선언적이고 간편하게 이용할 수 있도록 도와준다.
리액트 쿼리는 서버 데이터를 담을 상태를 만들고 useEffect로 상태에 데이터를 담는 모든 과정을 useQuery 단 한줄로 처리할 수 있다.
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 { isLoading, error, data } = useQuery({
queryKey: ['repoData'],
queryFn: () =>
fetch('https://api.github.com/repos/TanStack/query').then(
(res) => res.json(),
),
})
if (isLoading) 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>
)
}
https://tanstack.com/query/latesthttps://tanstack.com/query/latest/docs/react/overview
TanStack Query | React Query, Solid Query, Svelte Query, Vue Query
Powerful asynchronous state management, server-state utilities and data fetching for TS/JS, React, Solid, Svelte and Vue
tanstack.com