react-query
는 서버의 값을 클라이언트에 가져오거나, 캐싱, 값 업데이트, 에러핸들링 등 비동기 과정을 더욱 편하게 한다. 기존에 Redux, Mobx, Recoil과 같은 다양하고 훌륭한 상태 관리 라이브러리들이 있긴 하지만, 클라이언트 쪽의 데이터들을 관리하기에 적합할 순 있어도 서버 쪽의 데이터들을 관리하기에는 적합하지 않은 점들이 있는데 react-query
는 그러한 문제들도 해결해준다
const queryClient = new QueryClient();
<QueryClientProvider>
로 감싸준다quryClient
를 client prop으로 넘겨준다// src/index.js
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 { theme } from "./thems";
const rootElement = document.getElementById("root");
if (!rootElement) throw new Error("Failed to find the root element");
const root = ReactDOM.createRoot(rootElement);
//create a client
const queryClient = new QueryClient();
root.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</QueryClientProvider>
</React.StrictMode>
);
컴포넌트 파일 내에서 api를 fetch 하지 않고 따로 파일을 만들어서 관리한다
// src/routes/api.ts
export function fetchCoins() {
return fetch("api주소").then((response) =>
response.json()
);
}
useQuery hook은 두개의 인자를 필수로 요한다. 하나는 queryKey로 이는 고유식별자 역할을 하고, 나머지 하나는 fetcher 함수이다.
useQuery hook을 사용함으로써 페처함수를 불러오는 것과 로딩상태값, 에러상태 처리 등을 동시에 할 수 있다.
useQuery가 리턴하는 값은 두번째 인자의 페처함수에서 반환된 json값인data
,로딩 된 여부를 boolean값으로 리턴해주는isLoading
, 에러 상태들을 보여주는isError
등 다양한 값들이 있다.
useQuery를 사용하기 전과 후를 비교해보면
const [data, setData] = useState<ICoin[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
(async () => {
const response = await fetch("https://api.coinpaprika.com/v1/coins");
const json = await response.json();
setData(json.slice(0, 100));
setLoading(false);
})();
}, []);
// fetch 메서드를 사용했을 경우
const { isLoading, data } = useQuery<ICoin[]>("queryKey이름", fetcher함수명);
// react-query를 사용했을 경우
react-query를 사용해서 api 페칭을 하게되면 데이터를 캐시에 저장해 주기 때문에 페이지를 이동해도 화면 전환이 빠른 장점이 있다
또 isLoading, data등 같은 이름을 사용하게 되면 문제가 될 수 있는데,:
으로 이름을 새롭게지정해 줄 수 있다
const {isLoading : coinLaoding}
이 툴을 사용하면 캐시에 있는 query를 볼 수 있다.
// src/App.tsx
import { ReactQueryDevtools } from "react-query/devtools";
...
function App() {
return (
<>
<GlobalStyle />
<Router />
<ReactQueryDevtools initialIsOpen={true} />
</>
);
}