무려 취업 1년 만에 PO가 된 박우빈 씨가 번역해서 만든 사이트를 참고하여 학습하게 되었다.
> 링크 <
(되게 마인크래프트 복돌 링크 같네)
React Query는 일반적인 상태 관리 라이브러리가 아니다.
Jotai, Zustand 같은 상태 관리 라이브러리들은 클라이언트의 상태를 다루기에는 매우 뛰어날지 몰라도, 비동기나 서버 같은 상태를 관리하는 데에 사용하기에 효과적이지 않다.
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 "로딩중...";
if (error) return "에러가 발생했습니다: " + 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>
);
}
(여기서부턴 학습하기 전의 내용이므로 굳이 보지 않아도 되고 다음 제목으로 넘어가면 된다)
내용을 보게 되면 우선 App에서 Example Component를 불러오는 식이다. 그렇다면 실행할 때 Example이 보인다.
isPending, error, data가 있는데 아직 제대로 배우지 않았지만 useQuery에서 isPending, error, data를 받아올 수 있는 것으로 보인다. isPending은 비동기 방식이다 보니 아직 받아오지 못한 상태일 때를 보고, error는 받아오는 중 오류가 발생했을 때일 것이다. data는 값을 받아왔을 때 보관하는 곳으로 예상된다.
queryKey, queryFn이 있는데 queryKey는 구분하는 Key고 queryFn에서 REST API나 웹 사이트에 있는 걸 받아와서 데이터를 받아오는 것으로 보인다.
다만 queryKey는 지금은 망한 Recoil의 key 정도를 생각해 보면 될 것 같다. 아마 의도는 다를 것이다.
const textState = atom({
key: 'textState',
default: '',
});
여기서 놀라운 사실은 코드 몇 줄로 이 많은 작업들을 할 수 있다는 점이다. AI가 작성하는 걸 보고 알게 된 내용이지만, 저 코드를 다른 파일에 넣고 return 값을 이용한다면 함수 호출만으로도 클라이언트 단계의 상태 관리 라이브러리와 유사하게 써먹을 수 있다.
npm i @tanstack/react-query
pnpm add @tanstack/react-query
yarn add @tanstack/react-query
bun add @tanstack/react-query
bun을 코딩애플 유튜브에 본 사람들은 알겠지만 빠르다.
<script type="module">
import React from 'https://esm.sh/react@18.2.0'
import ReactDOM from 'https://esm.sh/react-dom@18.2.0'
import {QueryClient} from 'https://esm.sh/@tanstack/react-query'
</script>
(솔직히 소규모 프로젝트를 CDN으로 하는 변태들이 있을까)
eslint-plugin-query라는 것이 있는데 문법 오류나 버그를 잡아준다.
npm i -D @tanstack/eslint-plugin-query
pnpm add -D @tanstack/eslint-plugin-query
yarn add -D @tanstack/eslint-plugin-query
bun add -D @tanstack/eslint-plugin-query
내용이 생각보다 많아서 다음 편으로 가야 할 것 같다.