저는 얼마 전 블로그를 둘러보다가 React-Query라는 것을 보고 알아보며 정말 좋은 라이브러리라고 생각이 들어서 이렇게 더 잘 정리해서 사용하기 위해 오늘 이렇게 글을 쓰게 되었습니다

공식 문서에서는 React-Query를 이렇게 설명하고 있습니다
fetching, caching, 서버 데이터와의 동기화를 지원해주는 라이브러리
쉽게 말하자면 fetching, caching과 관련된 비동기관련 처리과정을 도와주는 라이브러리입니다

npm install @tanstack/react-query @tanstack/react-query-devtools
이렇게 react-query를 설치해줍니다 dev-tools는 선택사항이긴 하지만 devtools을 사용하면 패칭한 데이터를 쉽게 관리할 수 있습니다
데이터를 GET하기 위한 api에 쓰고 첫번째 파라미터로 unique Key가 들어가고, 두번째 파라미터로 비동기 함수(api호출 함수)가 들어갑니다 return 값은 api의 성공, 실패 여부, api return 값을 포함한 객체입니다
예시
import { useQuery } from 'react-query';
import axios from 'axios';
const fetchData = async () => {
const { data } = await axios.get('https://api.example.com/data');
return data;
};
const MyComponent = () => {
const { data, error, isLoading } = useQuery('myData', fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error loading data</div>;
return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default MyComponent;
값을 바꿀 때 사용하고 return 값은 useQuery와 동일합니다
예시
import { useMutation } from 'react-query';
import axios from 'axios';
const postData = async (newData) => {
const response = await axios.post('https://api.example.com/', newData);
return response.data;
};
const Example = () => {
const mutation = useMutation(postData);
const handleSubmit = () => {
mutation.mutate({ name: 'BAE', age: 17 });
};
if (mutation.isLoading) return <div>loading...</div>;
if (mutation.isError) return <div>Error</div>;
if (mutation.isSuccess) return <div>성공함!!</div>;
return (
<div>
<button onClick={handleSubmit}>제출!</button>
</div>
);
};
export default Example;
오늘은 React Query에 대해 이야기해 보았는데요 여러 가지 장점을 가진 React Query 라이브러리를 통해 더 간편하고 효율적으로 서버와 소통할 수 있었으면 좋겠습니다
| [React] 제어 컴포넌트 VS 비제어 컴포넌트 (4) | 2024.11.23 |
|---|---|
| [React] React에서 key 값은 왜 필요할까? 🔑 (3) | 2024.11.08 |
| React-Hook-Form으로 효율적으로 form 관리하자~! (9) | 2024.10.28 |
| Zustand란 뭘까? 🐻 (2) | 2024.10.16 |
| [React] Context API란? (6) | 2024.10.16 |