React Query는 데이터 Fetching, 캐싱, 동기화, 서버 쪽 데이터 업데이트 등을 쉽게 만들어 주는 React 라이브러리이다.
1. App 컴포넌트를 <QueryClientProvider client={queryClient}> 로 감싸준다.
```
const queryClient = new QueryClient();
root.render(
<>
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</QueryClientProvider>
</>,
);
```
2. api fetching을 다른 파일에서 진행하고, json 파일을 리턴받는다
3. useQuery() 함수를 사용한다.
- 인자로는 **data의 이름**과, **fetch 함수**를 준다.
- 최소 반환은 **isLoading**<boolean> 값과 **data**<fetch 함수 return 타입>가 있다.
4. 예시
- api.ts
```
export function fetchCoins() {
return fetch('https://api.coinpaprika.com/v1/coins').then((res) =>
res.json(),
);
}
```
- Coins.tsx
```
const { isLoading, data } = useQuery<ICoin[]>(['allCoins'], fetchCoins);
```
useQuery(data 이름, fetch 함수) 에서 data 이름은 고유해야 하고, fetch 함수에 인자가 필요하다면 단순 함수 이름만이 아닌, () ⇒ 함수이름(인자)의 형식으로 전달해야한다.
const {isLoading, data} = useQuery(data 이름, fetch 함수) 에서 isLoading과 data가 여러개라면 js 문법을 통해 이름을 할당할 수 있다.
const { isLoading: infoLoading, data: infoData } = useQuery<IInfoData>(
['info', coinId],
() => fetchCoinInfo(coinId!),
);
const { isLoading: tickersLoading, data: tickersData } = useQuery<IPriceData>(
['tickers', coinId],
() => fetchCoinTickers(coinId!),
);
const loading = infoLoading || tickersLoading;
useQuery의 세번째 인자로 { refetchInterval: 시간(ms) }을 줄 수 있다.
해당 인자를 통해 useQuery에서 시간 주기에 따라 자동으로 데이터를 불러온다.
The process of saving to useState may be dordle done in a single, streamlined chunk of code by combining the useEffect and async await methods.