[React] React Query v5 (TanStack Query) 사용해 보기

@eunjios·2023년 12월 6일
1
post-thumbnail

왜 Tanstack Query를 사용해야 하는가?

TanStack Query (FKA React Query) is, in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.

커스텀 훅을 사용해서 HTTP 통신을 해왔는데 갑자기 웬 Tanstack Query 인가?

  1. 리액트 공식 문서에서 데이터를 fetch 해올 때 useEffect 를 사용하는 방식을 권장하지 않는다.
  2. 로딩 및 에러, 캐싱 등 다양한 기능을 간단히 구현할 수 있다.
  3. 캐싱 기능을 간단히 구현하여 fetch 를 덜 해올 수 있다.

시작은 공식 문서였다. useEffect 를 사용해서 데이터를 가져오고 있었는데, 이것이 좋지 않은 방법이라고 하니 이 방식을 고수할 순 없었다. 실제로 사용해 보니 다양하고 강력한 기능을 지원하고 있어서 만족감이 컸다. 무엇보다 내 커스텀 훅에는 없었던 캐싱 기능까지 가지고 있어서 사용자 경험 측면에서도 훨씬 좋은 방법이라는 생각이 들었다.


서버 데이터 fetch 해오기 - useQuery

import useQuery

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

컴포넌트 내부에서 useQuery 사용하기

const { data, isPending, isError, error } = useQuery({
  queryKey: [QUERY_KEY],  // 식별자
  queryFn: QUERY_FUNCTION // HTTP 요청 함수 (Promise를 반환하는 함수)
});

useQuery 를 통해 data isPending isLoading isError error 등 다양한 상태를 사용할 수 있다. queryFn 에 Promise를 반환하는 HTTP 요청 함수를 지정하고, queryKey 에는 해당 요청을 식별하는 키를 지정한다. queryKey 를 통해 HTTP 요청을 식별하고 캐싱에 활용할 수 있다.

▶️ 더 다양한 useQuery API

QueryClientProvider 로 감싸기

import { QueryClientProvider, QueryClient } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <SomeComponent router={router} />
    </QueryClientProvider>
  );
}

QueryClientProvider로 최상위 컴포넌트를 감싸는 것을 잊지말자.

예시

import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
import LoadingIndicator from '../UI/LoadingIndicator.jsx';
import ErrorBlock from '../UI/ErrorBlock.jsx';

export default function Products() {
  const fetchProducts = () => axios.get('/products').then(({ data }) => data);
  
  const { data, isPending, isError, error } = useQuery({
    queryKey: ['products'],
    queryFn: fetchProducts
  });
    
  if (isPending) {
    return <LoadingSpinner />;
  }
  
  if (isError) {
    return <ErrorBlock message={error.info?.message || 'Failed to fetch'}/>'
  }
  
  return (
    <ul>
      {data?.map((product) => (
        <li>
          <ProductItem product={product} />
        </li>
      ))};
    </ul>
  );
}

위와 같이 로딩 및 에러 상태에 따라 다르게 렌더링 할 수 있다.


서버 데이터 변경하기 - useMutation

import useMutation

import { useMutation } from '@tanstack/react-query';

컴포넌트 내부에서 useMutation 사용하기

위에서는 컴포넌트가 마운트 될 때 서버로부터 데이터를 fetch 해왔다. 그러나 서버 데이터를 변경하는 요청은 (POST, DELETE 등) 대부분 특정 이벤트가 발생할 때 실행되어야 한다. 이는 useMutationmutate 를 사용하여 구현할 수 있다.

const { mutate } = useMutation({
  mutationFn: MUTATION_FUNCTION,
  onSuccess: () => {
    // 요청 성공 후 실행될 코드
  },
});

const submitHandler = () => {
  mutate({/* MUTATION_FUNCTION으로 넘길 파라미터 */});
}

▶️ 더 다양한 useMutation API

참고로 onSuccess 코드 블럭에는 주로 queryClient.invalidateQueries(QUERY_KEY) 가 포함된다. invalidateQueries 는 해당 키의 데이터를 초기화 하고, 이는 해당 키의 요청을 다시 실행시킨다. 예시는 아래 코드를 참고하자.

예시

import axios from 'axios';
import { useQuery, useMutation } from '@tanstack/react-query';
import LoadingIndicator from '../UI/LoadingIndicator.jsx';
import ErrorBlock from '../UI/ErrorBlock.jsx';
import { queryClient } from '../../util/http.js';

export default function Products() {
  const fetchProducts = () => axios.get('/products').then(({ data }) => data);
  const createNewProduct = (product) => axios.post('/products', { product });
  
  const { data, isPending, isError, error } = useQuery({
    queryKey: ['products'],
    queryFn: fetchProducts
  });
  
  const { mutate } = useMutation({
    mutationFn: createNewProduct,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['products'] });
    }
  });
  
  const createNewProductHandler = () => {
    const product = {
      id: Date.now(),
      title: '제품 이름', // 편의상 하드 코딩
      price: 10000
    };
    mutate(product);
  };
  
  if (isPending) {
    return <LoadingSpinner />;
  }
  
  if (isError) {
    return <ErrorBlock message={error.info?.message || 'Failed to fetch'}/>'
  }
  
  return (
    <>
      <button onClick={createNewProductHandler}>Add New Product</button>
      <ul>
        {data?.map((product) => (
          <li>
            <ProductItem product={product} />
          </li>
        ))};
      </ul>
    </>
  );
}

마치며

지금까지 커스텀 훅을 만들어서 HTTP 통신 했던 나...
이렇게 편한 라이브러리가 있었다니.....! 😮✨

직접 사용해보니 무엇보다 캐시 기능이 마음에 들었다. 예를 들어 detail 페이지에 들어갈 때마다 서버에 HTTP 요청을 보내서 데이터를 fetch 해 왔는데, 이전에 보낸 요청이라면 로딩 시간 없이 이전 데이터를 바로 사용할 수 있게 됐다.

아직 enabled 이나 staleTime 정도만 사용해 봤는데 앞으로 더 많은 기능을 잘 쓸 수 있는 방법에 대해 고민해야겠다. UX도 개선할 수 있고, 코드 짜는 사람 입장에서도 편하니 앞으로 자주 사용할 것 같다.


References

profile
growth

1개의 댓글

comment-user-thumbnail
2024년 8월 17일

Excel in NURS FPX 4050 Assessment: Expert Online Tutoring Services

Maximize your success in NURS FPX 4050 assessment with our specialized tutoring services. Tailored support from Assessment 1 to 4 empowers you to excel in your nursing program and advance your career.

Introduction to NURS FPX 4050 Series Assessment
The NURS FPX 4050 series is designed to challenge and enhance your understanding of advanced nursing practices and their impact on patient outcomes. Spanning from NURS FPX 4050 Assessment 1 to NURS FPX 4050 Assessment 4, this series tests your ability to apply critical thinking and evidence-based practices in real-world healthcare settings.

Targeted Tutoring for Unmatched Achievement
Our tutoring services offer targeted support for the NURS FPX 4050 series, ensuring that you have the knowledge and skills necessary to excel. Whether you are preparing for NURS FPX 4050 Assessment 2 https://experttutors.info/nurs-fpx4050-assessment-2/ or need in-depth guidance for NURS FPX 4050 Assessment 3, our tailored approach is designed to meet your individual needs.

Personalized Learning Experiences
We understand that each student's learning journey is unique. That's why we provide personalized tutoring plans that focus on your specific areas of improvement, ensuring that you're well-prepared for NURS FPX 4050 Assessment 4 and all other assessments in the series.

Access to Nursing Practice Expert
Our team of tutors includes experienced nursing professionals who specialize in advanced nursing practices. Their expertise ensures that you receive the highest quality guidance for NURS FPX 4050 Assessment 1 and beyond, equipping you with the competencies needed for success in your nursing career.

Fast-Track Your Success in One Billing Cycle
Our goal is to help you complete your nursing program efficiently and with excellence. With focused tutoring for NURS FPX 4050 Assessment 2 and NURS FPX 4050 Assessment 3, we aim to accelerate your learning process, enabling you to achieve your academic and professional goals more quickly.

Comprehensive Academic Support
From "Write my assessment" services to "Online assessment help," we offer a comprehensive range of resources designed to support your success in the NURS FPX 4050 series. Our goal is to ensure you are thoroughly prepared for NURS FPX 4050 Assessment 4 and ready to make a positive impact in the nursing field.

Your Pathway to Advanced Nursing Excellence
Choosing our tutoring services for the NURS FPX 4050 series is a critical step towards achieving excellence in advanced nursing practices. With personalized support, expert guidance, and comprehensive resources, you're on the path to excelling in your assessments and advancing your nursing career.
Take your nursing career to the next level with our expert NURS FPX 4050 assessment tutoring. Contact us today to learn how we can help you achieve your goals and become a leader in the nursing profession.

답글 달기