tanstack query란🤔
서버 상태를 관리하기 위한 라이브러리
(vs 클라이언트 상태 관리_redux,zustand등등)
tanstack query 훅🪝
- useQuery
- get : R
- 서버에서 데이터를 가져오는 데 사용
- 결과는 자동으로 캐싱되고, 다시 같은 데이터를 요청하면 캐시에서 가져와 빠르게 보여줌
- 데이터가 변했을 때, 자동으로 갱신(refresh)
const {
data: todos,
isPending,
isError,
} = useQuery({
queryKey: ["todos"],
queryFn: fetchTodos,
});
- useMutation
- modify : CUD
- 데이터를 생성(Create), 수정(Update), 삭제(Delete)할 때 사용
- 서버에 변경 요청을 보내고, 성공/실패 결과를 알려줌
- 요청 후 데이터를 다시 가져오려면 수동으로 invalidateQueries를 호출해야 해야함
const { mutate } = useMutation({
mutationFn: addTodo,
});
...
return(
<form
onSubmit={(e) => {
e.preventDefault();
const newTodoObj = { title: todoItem, isDone: false };
// useMutation 로직 필요
mutate(newTodoObj);
}}
>
)
- invalidateQueries
- refresh
- 특정 데이터(쿼리)를 다시 가져오게 함(refresh)
- 캐시를 지우고 서버에서 최신 데이터를 가져오게 만들어줌
- 보통 useMutation으로 데이터 변경 후 호출
const { mutate } = useMutation({
mutationFn: addTodo,
onSuccess: () => {
queryClient.invalidateQueries(["todos"]);
},
});
LifeCycle
상태 | 설명 |
fresh | - 데이터를 새로 패칭할 필요가 없는 상태 - staleTime이 지나지 않은 상태로, 캐시 데이터를 그대로 사용할 수 있음 |
stale | - 데이터를 새로 패칭해야 하는 상태 - staleTime이 지난 후로, 새로운 데이터를 가져오기 위해 쿼리가 실행 |
active | - 현재 컴포넌트에서 사용 중인 쿼리 상태 - 컴포넌트가 마운트되어 쿼리를 사용하고 있을 때 |
inactive | - 더 이상 사용되지 않는 쿼리 상태 - 컴포넌트가 언마운트되거나 쿼리가 더 이상 필요하지 않을 때 |
deleted | - 캐시에서 제거된 쿼리 상태 - gcTime 이 지나면 쿼리가 캐시에서 삭제되어 이 상태가 됨 |
fetching | - 데이터를 서버에서 가져오고 있는 상태 - 이 상태에서는 isFetching이 true로 설정됨 |
Overview | TanStack Query React Docs
TanStack Query (FKA React Query) is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating serve...
tanstack.com
'리액트' 카테고리의 다른 글
[React]axios (0) | 2024.11.26 |
---|---|
[React]Redux (1) | 2024.11.11 |
[React]context api (0) | 2024.11.11 |
[React]form태그 비제어 (0) | 2024.11.06 |
[React]memo(React.memo), useCallback,useMemo (1) | 2024.11.05 |