Just Do IT!

[React Native] react-query 이용하기 본문

개발 공부/React Native

[React Native] react-query 이용하기

MOON달 2023. 1. 5. 19:46
728x90
React-Query란?
  • server state, 비동기 데이터를 관리하기 위한 라이브러리
  • useQuery hook 안에서 API get 요청을 담당하고, API 요청 결과 및 다양한 상태들을 바로 사용할 수 있다
  • Redux, thunk 사용하지 않아도 되서 훨씬 간결하다
  • 한 번 API 요청 시 queryKey가 API 요청 결과를 cache에 저장하고, caching된 API 요청은 cache memory에서 빠르게 불러온다
  • key-value 구조로 되어 있다.

 

 

 

 

설치하기
$ npm i react-query --save
$ yarn add react-query

 

 

App.js 에서 최상위 컴포넌트 감싸주기
...
import { QueryClient, QueryClientProvider } from "react-query";

...

// access the client
const queryClient = new QueryClient();

export default function App() {
  
  ...

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider theme={isDark ? darkTheme : lightTheme}>
        <NavigationContainer theme={isDark ? DarkTheme : DefaultTheme}>
          <StatusBar />
          <Root />
        </NavigationContainer>
      </ThemeProvider>
    </QueryClientProvider>
  );
}
  • import 도 해줘야 오류가 나지 않는다.
  • queryClient가 최상위에 있기 때문에 내부의 모든 컴포넌트 내에서 cache에 접근할 수 있다.
  • 어떤 컴포넌트에 있어도 cache memory는 하나이다

 

 

 

 

react-query로 코드 작성하기 (useQuery 사용)
// Movies.jsx

...

// useQuery
  const { data: nowPlayingData, isLoading: isLoadingNP } = useQuery(
    ["Movies", "NowPlayings"],
    getNowPlayings
  );
  
  ..
// api.js

// API 이용할 때 필요한 URL과 KEY
const BASE_URL = "https://api.themoviedb.org/3/movie";
const API_KEY = "b3eb8003c5ad8fa2915d1fe18d0ee5a0";

// slide (now playing) 불러오기
export const getNowPlayings = () =>
  fetch(`${BASE_URL}/now_playing?api_key=${API_KEY}&language=en-US&page=1`)
    .then((res) => res.json())
    .catch((error) => console.log(error));
    
    ...

 

  • server state는 useQuery에서 관리하기 때문에 useState가 필요 없다.
  • async-await로 작성할 필요 없이 그냥 fetch 해오면 된다.
  • 서버 요청을 보냈을 때 queryKey(=NowPlayings)를 검색하고 있으면 fetcher 함수를 실행하지 않고 데이터를 그대로 이용할 수 있게 하고, 없으면 fetcher 함수를 실행해서 key에 맞는 value를 저장한다.
  • fetch 요청을 받을 때는 useQuery라는 hook을 사용한다.

 

 

 

 

 

refetch
  • refresh를 했을 때 (새로고침) 한 번 더 받아오는 것
  • fetch 함수와 무관하게 retetch를 하는 것이다.
  • queryClient.refetchQueries => 여러 함수를 일괄적으로 refetch할 수 있다.

 

// Movies.jsx

...

// refresh
  const onRefresh = async () => {
    setIsRefreshing(true);

    // Movies를 가지고 있는 fetcher 함수가 모두 일괄적으로 실행된다
    await queryClient.refetchQueries(["Movies"]);
    setIsRefreshing(false);
  };
  
  ...

위에서 "Movies"가 공통된 queryKey이므로 이 "Movies"를 가진 fetcher 함수가 일괄적으로 실행된다.

 

 

 

 

 


이외의 자세한 것들은 공식문서 보기.

https://react-query-v3.tanstack.com/overview

 

Overview | TanStack Query Docs

React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze. Motivation

tanstack.com