Skip to content

Latest commit

 

History

History
205 lines (149 loc) · 6.71 KB

File metadata and controls

205 lines (149 loc) · 6.71 KB

💻 Migrating to TanStack Query(React) v4

스크린샷 2022-08-17 오후 2 20 01


📃 주요 변경 사항

@tanstack/react-query

  • v4부터 react-query에서 @tanstack/react-query로 패키지가 변경되었습니다. 따라서 설치와 import 할 때 주의해야 합니다.
$ npm i @tanstack/react-query
# or
$ pnpm add @tanstack/react-query
# or
$ yarn add @tanstack/react-query
  • 또한, Devtools는 별도의 패키지 설치가 필요합니다.
$ npm i @tanstack/react-query-devtools
# or
$ pnpm add @tanstack/react-query-devtools
# or
$ yarn add @tanstack/react-query-devtools
  • import 시, 다음과 같이 패키지명을 수정하면 됩니다.
// v3
- import { useQuery } from "react-query";
- import { ReactQueryDevtools } from "react-query/devtools";

// v4
+ import { useQuery } from "@tanstack/react-query";
+ import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

쿼리 키는 배열로 통일

  • v3에서는 queryKey를 문자열 또는 배열로 지정할 수 있었습니다. 문자열과 배열 모두 사용할 수 있었는데, 사실 React Query는 내부적으로는 항상 Array Keys로만 작동했습니다. 그리고 이를 v4에서는 배열로 통일하였습니다.
// v3
- useQuery("todos", fetchTodos);

// v4
+ useQuery(["todos"], fetchTodos);

status idle 상태 제거

  • v4부터 더 나은 오프라인 지원을 위한 fetchStatus가 도입되면서 기존의 idle이 무의미해졌습니다.
// v3
- status: "idle";

// v4
+ status: "loading";
+ fetchStatus: "idle";

fetchStatus가 추가

  • FetchStatus
  • TanStack Query(v4) 새로운 상태값인 fetchStatus가 추가되었습니다.
  • fetchStatus
    • fetching: 쿼리가 현재 실행 중입니다.
    • paused: 쿼리를 요청했지만, 잠시 중단된 상태입니다.
    • idle: 쿼리가 현재 아무 작업도 수행하지 않고 있습니다.

왜 status, fetchStatus 나눠서 다루는 걸까?

  • fetchStatus는 HTTP 네트워크 연결 상태와 좀 더 관련된 상태 데이터입니다.

    • 예를 들어, status가 success 상태라면 주로 fetchStatus는 idle 상태지만, 백그라운드에서 re-fetch가 발생할 때 fetching 상태일 수 있습니다.
    • status가 보통 loading 상태일 때 fetchStatus는 주로 fetching를 갖지만, 네트워크 연결이 되어 있지 않은 경우 paused 상태를 가질 수 있습니다.
  • 정리하자면 아래와 같다.

    • status는 data가 있는지 없는지에 대한 상태입니다.
    • fetchStatus는 쿼리 즉, queryFn 요청이 진행중인지 아닌지에 대한 상태입니다.
  • why-two-different-states


useQueries

  • v4부터 useQueries는 인자로 queries 프로퍼티를 가진 객체를 넘겨줄 수 있습니다.
  • queries의 값은 쿼리 배열인데, 이는 v3에서 useQueries에게 넘겨주던 쿼리 배열과 동일합니다.
// v3
useQueries([
  { queryKey1, queryFn1, options1 },
  { queryKey2, queryFn2, options2 },
]);

// v4
useQueries({
  queries: [
    { queryKey1, queryFn1, options1 },
    { queryKey2, queryFn2, options2 },
  ],
});

networkMode

  • 기본적으로 react-query는 promise를 반환하는 모든 것에 사용할 수 있는 비동기 상태 관리 라이브러리이며, 이는 axios와 같은 data fetching 라이브러리와 가장 많이 사용됩니다.
  • 그렇기 때문에 네트워크 연결이 없는 경우 기본적으로 query와 mutation이 일시중지 됩니다. 이때, 이전 동작을 실행하려면 networkMode를 설정해주면 됩니다.
new QueryClient({
  defaultOptions: {
    queries: {
      networkMode: "offlineFirst", // (+)
    },
    mutations: {
      networkMode: "offlineFirst", // (+)
    },
  },
});
  • networkMode의 설정값은 3가지가 있습니다.
    • online: 오프라인 상태에서 network 연결이 있기 전까지 fetch를 하지 않고, 이때 쿼리의 상태를 fetchStatus:paused로 표시합니다.
    • always: 오프라인 상태에서도 온라인처럼 fetch를 시도합니다. 오프라인 상태에서 요청을 보내는 것이니 status:error 상태가 됩니다.
    • offlineFirst: v3에서의 동작과 같습니다. queryFn 최초 호출 후 retry를 멈춥니다.

Query Filters

  • query filter는 query와 일치하는 특정 조건을 가진 객체입니다.
  • 지금까지 필터 옵션은 대부분 boolean flag 조합이었습니다. 하지만 이러한 flag를 조합하면 불가능한 상태가 발생할 수 있습니다.
active?: boolean
  - When set to true it will match active queries.
  - When set to false it will match inactive queries.
inactive?: boolean
  - When set to true it will match inactive queries.
  - When set to false it will match active queries.
  • 예를 들어 위와 같은 active, inactive 두 옵션은 서로 상호 배타적입니다. 이 둘 모두를 false으로 설정한다면? 이는 말이 되지 않습니다.
  • v4부터는 이를 type이라는 속성으로 통일시켜서 의도를 더 잘 보여줄 수 있게 되었습니다.
// v3
- active?: boolean
- inactive?: boolean

// v4
+ type?: 'active' | 'inactive' | 'all'
  • type 속성은 기본적으로 all로 설정되며, active 또는 inactive 쿼리만 일치하도록 선택할 수 있습니다.
// Cancel all queries
await queryClient.cancelQueries()// Remove all inactive queries that begin with `posts` in the key
queryClient.removeQueries({ queryKey: ['posts'], type: 'inactive' })// Refetch all active queries
await queryClient.refetchQueries({ type: 'active' })// Refetch all active queries that begin with `posts` in the key
await queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' })

React18 지원

  • v4는 React18에대한 최고 수준의 지원과 함께 새로운 기능을 제공합니다.

타입스크립트