> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined-1/react-with-typescript/react/5./2-react-query.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 2) React Query

## 1. Intro

React에서 데이터를 API로 불러올 때는 일반적으로 다음과 같이 작성합니다.

```jsx
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");

useEffect(() => {
  setLoading(true);
  fetch("/api/users")
    .then(res => res.json())
    .then(setData)
    .catch(() => setError("에러 발생"))
    .finally(() => setLoading(false));
}, []);
```

* 위 코드는 매번 loading설정, error설정, data를 직접 관리해줘야합니다.
* 캐싱기능이나, 재용청 및 새로고침등은 직접 구현해야 합니다.&#x20;
* 하지만 React Query를 사용하는경우 위 기능들에 대한 추기 기능 구현 없이 간단하게 처리할 수 있습니다.

## 2. React Query

**React Query**는 **서버 상태(**&#xC608;: API 요청 결과)를 **효율적으로 관리**하기 위한 라이브러리입니다. `useState`나 `Redux`가 관리하는 **클라이언트 상태(Client State)** 와 달리, 서버 상태는 **서버에서 가져와야 하며, 클라이언트 단독으로 생성할 수 없**습니다. 주로 **`Axios`** 같은 HTTP 클라이언트와 함께 사용되며, 다음과 같은 기능들을 제공합니다.

| 기능                 | 설명                                                                                                                                          |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **자동 캐싱**          | `useQuery`를 이용하여 데이터를 패치할 수 있으며, 동일한 key를 가진 요청에 대해서는 자동으로 캐시를 사용한다.                                                                        |
| **자동 로딩/에러 상태 관리** | `isLoading`, `isError` 등 내장 상태값 제공하기 때문에 useState로 별도로 관리할 필요가 없다.                                                                          |
| **자동 리패치**         | 탭 변경 시 및 새로고침 시 자동 재요청되독 설정도 가능하며, 일정시간 간격으로 갱신도 가능하다                                                                                       |
| **서버 상태 공유**       | React Query의 캐시는 단일전역 저장소에 저장되어 여러 컴포넌트에서 공유하여 사용한다.                                                                                        |
| **mutation 처리**    | <p></p><p><code>useMutation</code> 훅을 통해 POST/PUT/DELETE 같은 데이터 변경 요청을 처리할수있으며,   성공/실패 시 자동 캐시 무효화(Invalidate)기능이 추가되어있다.(무효화시 자동 리패치)</p> |

## 3.  React Query 동작 흐름

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2FugFHICze8y2Ok5jRfllS%2Fimage.png?alt=media&amp;token=7fc773a7-6664-4241-a2ca-361a6b2fb1dd" alt=""><figcaption></figcaption></figure>

1. **Fetch**
   * `useQuery` 훅이 실행되면 데이터를 패치(fetch)합니다.
   * API 요청 중에는 `isLoading` 상태가 됩니다.
2. **Fresh**
   * 요청 성공 후 캐시에 데이터가 저장되면 **Fresh(신선한 상태)** 가 됩니다.
   * 이때는 staleTime 동안 **최신 데이터**로 간주되어 추가 요청을 하지 않습니다.
3. **State (Stale)**
   * 시간이 지나 staleTime이 만료되면 **Stale(오래된 상태)** 가 됩니다.
   * UI는 기존 데이터를 계속 보여주지만, 백그라운드에서 **자동 리패치**를 트리거할 수 있습니다.
   * `isFetching` 상태가 함께 켜질 수 있습니다.
4. **Inactive**
   * 이 쿼리를 사용하던 컴포넌트가 언마운트되면 쿼리는 **Inactive(비활성)** 상태가 됩니다.
   * 하지만 캐시는 남아 있고, `cacheTime` 동안 보관됩니다.
5. **Deleted**
   * `cacheTime`이 지나면 캐시가 완전히 제거되어 **Deleted** 상태가 됩니다.
   * 다시 컴포넌트가 같은 쿼리 키로 마운트되면 처음부터 Fetch 단계가 시작됩니다.

## 4. 사용방법

1. react-query 패키지 설치

`npm install @tanstack/react-query`

2. main.tsx에 QueryClient설정

```jsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';

const queryClient = new QueryClient();

export default function Root() {
  return (
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  );
}
```

3. 데이터 조회시 `useQuery`훅 사용

```jsx
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

function Users() {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['users'], // 캐시 구분용 키
    queryFn: () => axios.get('/api/users').then(res => res.data),
  });

  if (isLoading) return <p>로딩중...</p>;
  if (isError) return <p>에러 발생</p>;

  return (
    <ul>
      {data.map((user: any) => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}
```

4. 데이터 변경시 `useMutation`훅 사용

```tsx
import { useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';

function AddUser() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: (newUser: { name: string }) =>
      axios.post('/api/users', newUser),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] }); // 캐시 무효화 → 새로 fetch
    }
  });

  return (
    <button onClick={() => mutation.mutate({ name: '새 사용자' })}>
      사용자 추가
    </button>
  );
}

```
