React Query의 용도는 주로 서버 상태 관리(Server State Management)를 효율적으로 처리하는 것입니다. 서버 상태는 클라이언트 애플리케이션이 서버에서 데이터를 가져오고, 이를 사용하며, 서버와 동기화하는 데 사용되는 데이터를 말합니다. React Query는 이를 간단하고 효율적으로 처리하는 도구입니다.
import { useQuery } from '@tanstack/react-query';
const fetchData = async () => {
const res = await fetch('/api/data');
return res.json();
};
const Component = () => {
const { data, isLoading, error } = useQuery(['key'], fetchData);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <p>Data: {data}</p>;
};
import { useMutation, useQueryClient } from '@tanstack/react-query';
const postData = async (newData) => {
const res = await fetch('/api/data', {
method: 'POST',
body: JSON.stringify(newData),
headers: { 'Content-Type': 'application/json' },
});
return res.json();
};
const Component = () => {
const queryClient = useQueryClient();
const mutation = useMutation(postData, {
onSuccess: () => {
queryClient.invalidateQueries(['key']); // 데이터 다시 가져오기
},
});
const handleSubmit = () => {
mutation.mutate({ name: 'New Data' });
};
return <button onClick={handleSubmit}>Submit</button>;
};
import { useInfiniteQuery } from '@tanstack/react-query';
const fetchItems = async ({ pageParam = 1 }) => {
const res = await fetch(`/api/items?page=${pageParam}`);
return res.json();
};
const Component = () => {
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery(
['items'],
fetchItems,
{
getNextPageParam: (lastPage) => lastPage.nextPage || undefined,
}
);
return (
<div>
{data.pages.map((page, i) => (
<div key={i}>
{page.items.map((item) => (
<p key={item.id}>{item.name}</p>
))}
</div>
))}
{hasNextPage && <button onClick={() => fetchNextPage()}>Load More</button>}
</div>
);
};
생산성 향상:
재현 가능한 데이터 흐름:
성능 최적화:
타입스크립트 지원:
React Query는 데이터 중심 애플리케이션에서 불필요한 상태 관리 코드를 제거하고, 간결하고 효율적인 데이터 관리를 가능하게 합니다.
이미 Recoil 같은 전역 상태관리를 사용하고 있으면 React-Query 같은 경우는 서버 상태 관리 용도로 사용하면 된다.