React 애플리케이션에서 서버 상태를 관리하여 쉽게 처리 할 수 있도록 도와주는 라이브러리이다.
예전 이름은 React query이며 사용해보고 싶었는데 드뎌 사용해보았다.
📌 생산성 향상
우선 내가 생각하는 가장 큰 장점이다!!
기존 비동기 작업 시에는 useState와 useEffet훅을 사용해서 작업했다면
이 둘을 합쳐서 사용하기 때문에 생산성이 확 향상되었다
📌 간편한 상태 관리
앞선 이야기와 연결된 이야기로 하나로 손쉽게 관리하기 때문에
상태 관리가 비교적 간편하다
npm i @tanstack/react-query
// app.tsx
import { QueryClient} from '@tanstack/react-query';
return (
<QueryClientProvider client={QueryClient}>
...
</QueryClientProvider>
);
책 정보를 가져오는 api
const {data: booksData, isLoading: isBooksLoading} = useQuery<FetchRES>({
queryKey: ['books', location.search],
queryFn: async () => {
return await fetchBooks({
category_id: params.get(QUERYSTRING.CATEGORY_ID)
? Number(params.get(QUERYSTRING.CATEGORY_ID))
: undefined,
news: params.get(QUERYSTRING.NEWS) ? true : undefined,
limit: LIMIT,
currentPage: params.get(QUERYSTRING.PAGE)
? Number(params.get(QUERYSTRING.PAGE))
: 1,
});
},
});
queryKey와 queryFn만 설정해주면 손쉽게 비동기 작업을 처리해줄 수 있다.
const [booksData, setBooksData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
setError(null); // 이전 에러 초기화
try {
const data = await fetchBooks({
category_id: params.get(QUERYSTRING.CATEGORY_ID)
? Number(params.get(QUERYSTRING.CATEGORY_ID))
: undefined,
limit: LIMIT,
currentPage: params.get(QUERYSTRING.PAGE)
? Number(params.get(QUERYSTRING.PAGE))
: 1,
});
setBooksData(data);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
fetchData();
}, [location.search]);
확실히 코드가 간편해지고 짧아진 모습이다!!
역시 사람들이 많이 사용하는 것에는 이유가 다 있는 거 같다.
아직까지는 useState와 useEffet를 많이 사용해서 여기에 익숙하지만
앞으로 조금씩 사용해보며 tanstack Query에도 익숙해지도록 해야겠다.