
(사진 제공 완벽하다. 내 롤모델 '달미'가 되도록 오늘도 원스텝)
하! 글지기가 돌아왔습니당
난, 안오려했는데 손가락이 오자해서 왔지.
오늘의 TIL은
Section 24 리액트 쿼리/Tanstack 쿼리:간단하게 HTTP 요청처리
TIL1) Tanstack 쿼리가 뭔데
오늘 나는 Tanstack 쿼리에 대해 배웠다. Tanstack 쿼리는 리액트 애플리케이션에서 서버 상태를 관리하는 데 도움을 주는 라이브러리로, 데이터 페칭, 캐싱, 동기화, 업데이트를 쉽게 처리할 수 있다.
이 라이브러리는 서버와 클라이언트 간의 데이터 흐름을 간소화하고, 불필요한 리렌더링을 줄여 성능을 최적화하는 데 유용하다. Tanstack 쿼리를 사용하면 비동기 작업을 간단하게 관리할 수 있어 개발 생산성을 높일 수 있다.
import { useQuery } from '@tanstack/react-query';
function fetchData() {
return fetch('https://api.example.com/data')
.then(response => response.json());
}
function MyComponent() {
const { data, error, isLoading } = useQuery(['data'], fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
TIL2) 동적 쿼리 함수 및 쿼리 키
그중 Tanstack 쿼리에서 동적 쿼리 함수와 쿼리 키에 대해 배웠다. 동적 쿼리 함수는 다양한 매개변수를 기반으로 데이터를 가져올 수 있도록 도와주며, 쿼리 키는 각각의 쿼리를 고유하게 식별하는 역할을 한다.
쿼리 키를 적절히 사용하면 데이터 캐싱과 무효화를 효과적으로 관리할 수 있다. 이를 통해 필요한 데이터만 가져오고, 불필요한 네트워크 요청을 줄일 수 있다.
import { useQuery } from '@tanstack/react-query';
function fetchUserData(userId) {
return fetch(`https://api.example.com/user/${userId}`)
.then(response => response.json());
}
function UserComponent({ userId }) {
const { data, error, isLoading } = useQuery(['user', userId], () => fetchUserData(userId));
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
</div>
);
}
TIL3) 변형을 사용하여 데이터 변경
변형은 서버에 데이터를 추가, 수정, 삭제하는 등의 작업을 처리할 때 사용된다. 변형을 통해 서버 상태를 업데이트하고, 이를 클라이언트에 반영할 수 있다.
변형 후에는 쿼리를 무효화하여 최신 데이터를 가져오도록 할 수 있어 데이터 일관성을 유지하는 데 도움이 된다.
import { useMutation, useQueryClient } from '@tanstack/react-query';
function addUser(newUser) {
return fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newUser),
}).then(response => response.json());
}
function AddUserComponent() {
const queryClient = useQueryClient();
const mutation = useMutation(addUser, {
onSuccess: () => {
queryClient.invalidateQueries(['users']);
},
});
const handleAddUser = () => {
mutation.mutate({ name: 'New User', email: 'newuser@example.com' });
};
return (
<button onClick={handleAddUser}>
Add User
</button>
);
}
TIL4) 리액트 쿼리와 리액트 라우터
리액트 라우터는 클라이언트 측 라우팅을 관리하는 라이브러리로, 페이지 간 탐색을 쉽게 할 수 있도록 돕는다. 리액트 쿼리와 리액트 라우터를 함께 사용하면, 페이지 전환 시 필요한 데이터를 효율적으로 가져올 수 있다. 라우터의 경로 변경에 따라 쿼리를 트리거하고, 필요한 데이터를 미리 로드하여 사용자 경험을 개선할 수 있다.
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
function fetchPost(postId) {
return fetch(`https://api.example.com/posts/${postId}`)
.then(response => response.json());
}
function Post({ match }) {
const { data, error, isLoading } = useQuery(['post', match.params.postId], () => fetchPost(match.params.postId));
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data.title}</h1>
<p>{data.content}</p>
</div>
);
}
function App() {
return (
<Router>
<nav>
<Link to="/post/1">Post 1</Link>
<Link to="/post/2">Post 2</Link>
</nav>
<Switch>
<Route path="/post/:postId" component={Post} />
</Switch>
</Router>
);
}
질문거리
라우트 변경 시, 쿼리를 자동으로 무효화하고 데이터를 다시 가져오도록 설정할 수 있는 방법이 궁금합니다!
** 생각나시면 얼음 2개 올려주세요,,! 하하