React Query : 데이터 Fetching, 캐싱, 데이터 업데이트 등을 쉽게 만들어 주는 React 라이브러리
const [value, setValue] = useState<IValue[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
(async () => {
const response = await fetch("api_URL");
const json = await response.json();
setValue(json);
setLoading(false);
})();
}, []);
컴포넌트를 렌더리 할때 lodaing state를 useState()로 관리하고 useEffect()로 데이터를 fetching 한다. data fetching이 끝나면 value값에 할당하고 loading state를 변경해준다.
useQuery("data_key_name", fetchFunc)
useQuery("apiResult", async () { await fetch(...) })
코드의 결과로 아래 값을 리턴한다.
fetch를 사용할 때와는 다르게 loading state를 기본으로 제공해준다. fetching이 끝나면 데이터를 자동으로 캐싱하고 loading state를 false로 바꿔주기 때문에 loading state를 위한 useEffect 사용이 필요 없다.
자동으로 캐싱을 해주시때문에 페이지 전환시마다 fetching을 새로 하는 작업이 없다.
아래와 같은 여러가지 옵션을 제공한다.
//index.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "react-query";
import { ThemeProvider } from "styled-components";
import App from "./App";
import { darkTheme } from "./theme";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 0,
useErrorBoundary: true,
},
mutations: {
useErrorBoundary: true,
},
},
});;
const root = document.getElementById("root");
if (!root) {
throw new Error("Can't find root node");
}
ReactDOM.createRoot(root).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={darkTheme}>
<App />
</ThemeProvider>
</QueryClientProvider>
</React.StrictMode>
useQuery는 쿼리들을 묶어서 처리해주는 hook으로 자체적으로 옵션을 설정할 수 없지만 useQuery 안에 있는 쿼리에는 옵션을 설정할 수 있다.
React query docs : https://react-query-alpha.tanstack.com/overview
특히 Get 외의 요청을 처리하는 mutation에 대해서 알아보면 좋을것 같다.
React query mutation docs : https://react-query-alpha.tanstack.com/guides/mutations