React Query란?
- React Query는 React 애플리케이션에서 데이터를 관리하기 위한 라이브러리
- 서버 상태 및 데이터를 효과적으로 처리하고 캐시 관리를 제공
- 이를 통해 컴포넌트 간의 상태 공유와 관리, 비동기 데이터 요청 및 갱신을 보다 쉽게 처리
React Query의 특징
- 선언적 쿼리
데이터 요청 및 관리를 간단한 함수 호출로 처리할 수 있다.
- 인터랙티브 쿼리
컴포넌트에서 데이터를 간단하게 요청하고 갱신할 수 있다.
- 오프라인 쿼리
오프라인 상태에서도 캐시를 통해 데이터를 불러올 수 있다.
- Infinite Queries 및 Mutations
무한 스크롤과 데이터 변경을 쉽게 다룰 수 있다.
React Query의 핵심 개념
Query
데이터를 가져오는데 사용되는 함수. useQuery 훅을 통해 선언적으로 사용
const { data, isLoading, error } = useQuery('exampleQuery', fetchDataFunction);
Mutation
데이터를 변경하는데 사용되는 함수. useMutation 훅을 통해 사용
const mutation = useMutation(updateDataFunction);
Query Keys
Query의 고유 식별자로 사용되는 값. 중복을 방지하기 위해 사용
const { data } = useQuery(['exampleQuery', { id: 1 }], fetchDataFunction);
Query Invalidation
데이터 갱신 시에 캐시를 업데이트하는 기능
Query
예시 코드
import { useQuery } from 'react-query';
const fetchData = async () => {
const response = await fetch('/api/data');
return response.json();
};
function DataComponent() {
const { data, isLoading, error } = useQuery('exampleQuery', fetchData);
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div>
<h1>Data: {data}</h1>
</div>
);
}
Mutation
/ Invalidation
예시 코드
import { useMutation, useQueryClient } from 'react-query';
const updateData = async (newData) => {
const response = await axios({
method: 'post',
url: 'url',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
return response.json();
};
function UpdateDataComponent() {
const queryClient = useQueryClient();
const mutation = useMutation(updateData, {
onSuccess: () => {
queryClient.invalidateQueries('exampleQuery');
},
});
const handleUpdate = () => {
mutation.mutate('newData');
};
return (
<div>
<button onClick={handleUpdate}>Update Data</button>
</div>
);
}