이번 글은 "리액트 쿼리"에 대한 전반적인 내용을 담은 글이다. 리액트 쿼리가 무엇인지 시작해서, 코드는 어떻게 작성하는지? 언제 사용하는지 등등.. 이야기할 것이다.
제대로 시작하기 전에, 공식 문서가 궁금하다면?
공식 문서
https://tanstack.com/query/latest/docs/framework/react/examples/basic
React TanStack Query Basic Example | TanStack Query Docs
An example showing how to implement Basic in React using TanStack Query.
tanstack.com
위 링크 들어가면 리액트 쿼리의 베이직한 예시를 확인할 수 있다. (문서도 있으니 확인하자.)
리액트 쿼리란?
공식문서에서는 React-Query를 다음과 같이 설명하고 있다.
💡 fetching, caching, 서버 데이터와의 동기화를 지원해 주는 라이브러리
즉, React-Query는 프론트엔드에서 비동기 데이터를 불러오는 과정 중 발생하는 문제들을 해결해 준다는 것.
예시 코드
import { QueryClient, QueryClientProvider, useQuery } from "react-query";
const queryClient = new QueryClient();
const url = "https://61b88c9d64e4a10017d19053.mockapi.io/user";
const App = () => (
<div>
<QueryClientProvider client={queryClient}>
<ReactQueryProfile />
</QueryClientProvider>
</div>
);
const ReactQueryProfile = () => {
const { isPending, error, data } = useQuery({
queryKey: ["users"],
queryFn: () => fetch("https://61b88c9d64e4a10017d19053.mockapi.io/user").then(res => res.json())
});
if (error) return <div>failed to load</div>;
if (isPending) return <div>loading...</div>;
return <Profile library="React Query" data={data} />;
}
const Profile = ({library, data}) => (
<div>
<h1>Users from {library}</h1>
{data.map(user => <p>{user.level} developer <strong>{user.name}</strong></p>)}
</div>
)
export default App;
설치 >
npm install @tanstack/react-query
(원래는 npm install react-query 였는데,, 설치 방법도 바뀜)
devtool >
npm install @tanstack/react-query-devtools
(위 devtool은 선택사항이긴 함.)
언제 씀?
언제 React Query를 사용해야 할까?
React Query는 주로 서버 상태를 관리할 때 사용한다.
참고로 서버 상태란 API를 통해 가져오는 데이터로, 애플리케이션 외부에 존재하며 지속적인 동기화가 필요한 데이터를 말한다. (자체적으로 API를 만드는 것도 되고, 따로 만들어진 API를 가져오는 것도 괜찮다.)
(참고한 블로그)
- https://velog.io/@jay/10-minute-react-query-concept
- https://velog.io/@kandy1002/React-Query-%ED%91%B9-%EC%B0%8D%EC%96%B4%EB%A8%B9%EA%B8%B0
- https://musma.github.io/2023/09/14/react-query.html
- https://tech.kakaopay.com/post/react-query-1/
영상 - (우테코 테코톡 프론트엔드)
https://youtu.be/n-ddI9Lt7Xs?si=pKLzcI7dvEeovdS_
'FE > React' 카테고리의 다른 글
리액트 emotion 사용법 (2) | 2025.02.23 |
---|---|
리액트 zustand란? (0) | 2025.02.21 |
리액트 Swiper (슬라이더) 적용 (1) | 2025.01.27 |
리액트 - 유튜브 영상 넣기 (3) | 2024.11.27 |
리액트 - 카카오 Map API (10) | 2024.10.09 |