[유데미] React Query : React로 서버 상태 관리하기
📍React Query Dev Tools이란?
- 리액트 쿼리에서 기본 제공하며, 다양한 기능을 제공
- v4 부터 직접 import하게 바뀌었음!
npm i @tanstack/react-query-devtools
- Development 환경에서만 보여지므로 따로 -D 옵션으로 설치할 필요는 없다
📍기능
1️⃣key에 기반하여 쿼리를 보여준다
- 쿼리들의 상태
- 마지막 업데이트 타임스탬프
2️⃣반환된 데이터를 보여준다
3️⃣쿼리 탐색기 제공
📍사용방법
1️⃣npm install 후, query client를 생성한 컴포넌트 (App) 에서 import 해준다
2️⃣Provider 내부의 최하단에 devtools를 삽입
// App.tsx
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
// ...
const queryClient = new QueryClient();
function App() {
return (
// provide React Query client to App
<QueryClientProvider client={queryClient}>
<div className="App">
<h1>Blog Posts</h1>
<Posts />
</div>
<ReactQueryDevtools />
</QueryClientProvider>
);
}
3️⃣사이트 좌하단에 react query 모양 로고가 생기면 성공, 클릭으로 열고 닫을 수 있다
📍stale (만료)
- stale data만 data refetching이 가능하다
(data refetching이 발생하는 경우 : 컴포넌트 리마운트, 윈도우 리포커스 등..)
다른 창으로 넘어갔다가 다시 들어오면 data refetching 발생..
- stale time : 데이터가 만료됐다고 판단하는 최대 시간
(즉, stale time 경과후에 stale data 라고 판정)
이 stale time은 useQuery의 매개변수 객체에 추가할 수 있다! (단위 : ms)
const { data, isError, error, isLoading } = useQuery({
queryKey: ["posts"],
queryFn: fetchPosts,
staleTime: 2000,
});
- staleTime을 설정하고 나면, window refocus될 때마다
fresh -> (설정한 stale time 경과) -> stale 로 상태가 바뀌는 것을 devtools 에서 확인할 수 있다
- stale time의 기본값은 0이다
즉, stale time이 지정되어 있지 않으면, 항상 만료된 상태라는 것으로, 서버에서 데이터를 다시 가져와야 한다는 의미이다
이를 통해 클라이언트에 만료된 데이터를 제공할 위험이 줄어든다
📍staleTime vs cacheTime
- staleTime : data re-fetching 을 위해서 사용
- cache : 나중에 재사용될 수 있는 데이터를 다룸
active useQuery가 없으면, 기존 query는 cold storage에 보관됨
cache data는 cacheTime이 지나면 만료된다 (디폴트 : 5분)
(cacheTime은 마지막 active useQuery부터 측정)
cache가 만료되면, 데이터는 garbage collector에 의해 소실된다
(데이터를 새로 가져오지 않고 그냥 없어짐)
- 즉, cache는 fetching 중 표시할 백업 데이터 역할을 한다
화면에 최신 데이터만 표시해야하는 경우에는, cacheTime = 0 으로 설정하면 된다
📍참고
https://tanstack.com/query/v4/docs/react/devtools
Devtools | TanStack Query Docs
Wave your hands in the air and shout hooray because React Query comes with dedicated devtools! 🥳 When you begin your React Query journey, you'll want these devtools by your side. They help visualize all of the inner workings of React Query and will like
tanstack.com