TanStack Query Library Document - dev-team-projects/DeliTalk GitHub Wiki
์์ฑ์ : ์์ฑ์ค, ์ ํ์, ์ด์ค์
-
์๋ฒ ์ํ๋ฅผ ์๋์ผ๋ก ์บ์ฑ
ํฉ๋๋ค. -
๋ก๋ฉ/์๋ฌ ์ํ๋ฅผ ์ฝ๊ฒ ๊ด๋ฆฌ
ํฉ๋๋ค.- โก๏ธ
๋ฐ์ดํฐ ํจ์นญ ๋ก์ง์ ์์ฐ์ฑ๊ณผ ์ผ๊ด์ฑ ํฅ์
- โก๏ธ
- useEffect ๊ธฐ๋ฐ ์ฝ๋์ ๋ณต์ก์ฑ์ ์ค์ผ ์ ์์ต๋๋ค.
์ฃผ๋ก ์๋ฒ์์ ๊ฐ์ ธ์จ ๋ฐ์ดํฐ๋ฅผ ๊ด๋ฆฌํ๋๋ฐ ์ค์ ์ ๋ก๋๋ค.
GET /api/users
import { useEffect, useState } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
useEffect(() => {
setIsLoading(true);
setIsError(false);
axios
.get('/api/users')
.then((res) => {
setUsers(res.data);
})
.catch((err) => {
console.error(err);
setIsError(true);
})
.finally(() => {
setIsLoading(false);
});
}, []);
if (isLoading) return <p>Loading...</p>;
if (isError) return <p>Error fetching users</p>;
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
- ์ํ ๋ณ์(
isLoading
,isError
,users
)๊ฐ ๋ง์์ง๋๋ค. - ์๋ฌ ์ฒ๋ฆฌ, ๋ก๋ฉ ์ฒ๋ฆฌ ๋ฐ๋ณตํฉ๋๋ค.
- ์บ์ฑ ์์ โก๏ธ ๋งค๋ฒ ์๋ก ์์ฒญํฉ๋๋ค.
- ์ฌ์์ฒญ, refetch, stale control ๊ธฐ๋ฅ ์์ต๋๋ค.
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchUsers = async () => {
const { data } = await axios.get('/api/users');
return data;
};
function UserList() {
const {
data: users,
isLoading,
isError,
} = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
staleTime: 1000 * 60 * 5, // 5๋ถ๊ฐ ์บ์ฑ
});
if (isLoading) return <p>Loading...</p>;
if (isError) return <p>Error fetching users</p>;
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
- ๋ก๋ฉ/์๋ฌ ์ํ ์๋ ์ ๊ณต
- ๋ฐ์ดํฐ fetching ์ํ(loading, error, success)๋ฅผ ์๋์ผ๋ก ๊ด๋ฆฌํด UI ์ฒ๋ฆฌ๊ฐ ๊ฐํธํฉ๋๋ค.
-
queryKey
๋ก ์บ์ ๊ตฌ๋ถ ๋ฐ ์๋ ๊ด๋ฆฌ- ๋์ผํ ์ฟผ๋ฆฌ๋ฅผ ๊ตฌ๋ถํ๊ณ , ํจ์จ์ ์ผ๋ก ์บ์ฑ/๊ฐฑ์ ๊ด๋ฆฌ๊ฐ ๊ฐ๋ฅํฉ๋๋ค.
- ๋ฐฐ๊ฒฝ refetch
- ์ฌ์ฉ์๊ฐ ํ๋ฉด์ ๋จธ๋ฌด๋ ๋์์๋ ๋ฐ์ดํฐ ์ต์ ์ํ ์ ์งํฉ๋๋ค.
- ์บ์ฑ
- ๊ฐ์ ธ์จ ๋ฐ์ดํฐ๋ฅผ ์๋์ผ๋ก ์บ์ฑํ๊ณ ๊ด๋ฆฌํฉ๋๋ค.
- retry
- ์คํจ ์ ์๋ ์ฌ์๋๋ฅผ ํตํด ๋คํธ์ํฌ ๋ถ์์ ์ํฉ์๋ ์์ ์ฑ์ ํ๋ณดํฉ๋๋ค.
- ๋ก๋ฉ ์คํผ๋
- ๋ก๋ฉ ์ํ ๊ฐ์ผ๋ก ์คํผ๋ ๋ฑ UI ์์ ์์ฝ๊ฒ ์ฒ๋ฆฌํฉ๋๋ค.
- prefetch
- ํ์ด์ง ์ด๋ ์ ์ ๋ฐ์ดํฐ๋ฅผ ๋ฏธ๋ฆฌ ๊ฐ์ ธ์ ๋น ๋ฅด๊ฒ ์ ํํฉ๋๋ค.
- ์ฝ๋๊ฐ ๊ฐ๊ฒฐํ๊ณ ์ฌ์ฌ์ฉ์ฑ ๋์
- ์ ์ธ์ API ๋๋ถ์ ์ฝ๋ ์ ์ง๋ณด์์ฑ๊ณผ ์ฌ์ฌ์ฉ์ฑ์ ํฅ์ ์ํต๋๋ค.