[React] react-query 커스텀 훅으로 활용

김채운·2024년 4월 16일
0

React

목록 보기
26/26

프로젝트에서 각 컴포넌트에 필요한 부분에서 react-query의 useQuery와 useMutation을 사용해서 비동기 통신을 했는데 이렇게 하니 각 컴포넌트마다 분산되어 있어 어디에서 useQuery를 사용하고 useMutation을 사용했는지 또 어떤 queryKey를 사용했는지 한눈에 파악이 잘 안 됐기 때문에 invalidateQueries를 해줘야 하는지 컴포넌트마다 확인을 해야하는 불편함이 있었다. 그래서 우선 한 눈에 react-query코드를 파악하기 쉽게 custom hook으로 만들었다.

➡️ Custom Hook으로 만들었을 때의 이점

  • 각 컴포넌트에서 데이터에 접근해야 할 경우 useQuery를 매번 호출할 필요가 없다.

  • 여러 개의 쿼리 호출을 사용하는 경우 사용 중인 queryKey가 혼동이 될 수 있다. 따라서 커스텀 훅을 사용해서 쿼리를 호출하면 키를 혼동할 위험이 없다.

  • 사용하려는 쿼리 함수를 혼동할 위험도 없다. 커스텀 훅에 쿼리 함수를 모듈화 시켜 놓으면 각 컴포넌트에서 쿼리 함수를 하나씩 불러올 필요가 없다.

  • 업데이트가 필요할 경우 각 컴포넌트들을 업데이트 할 필요 없이 커스텀 훅만 업데이트 시키면 된다.

  • 서버로부터 데이터를 가져오는 비동기 통신 같은 데이터 로직을 UI에서 분리하고 추상화함으로써 컴포넌트들이 데이터에 직접 접근하는 것이 아니라 커스텀 훅과 같은 중간 계층을 통해 데이터에 접근할 수 있게 된다.

이러한 데이터 로직을 별도의 모듈로 분리하여 재사용 가능한 함수나 훅으로 만들어서 관리하면 데이터에 접근하는 방법이나 구현이 변경될 경우, 커스텀 훅의 구현만 업데이트하면 된다. 즉 UI의 컴포넌트들은 이 변경에 대해 신경쓰지 않아도 되며, 컴포넌트를 다시 업데이트할 필요가 없다. 따라서 코드의 재사용성과 유지보수성을 높일 수 있다.

✨ 컴포넌트가 데이터에 직접 접근하는 대신 커스텀 훅과 같은 중간 계층을 통해 데이터에 접근하는 것의 이점.

1. 코드의 재사용성: 데이터 로직을 분리하여 중복을 제거하고 재사용 가능한 훅으로 만들면, 각 컴포넌트에서 해당 훅을 사용하여 동일한 데이터 로직을 공유할 수 있다.

2. 유지보수성: 데이터 로직이 중앙화되면, 해당 로직을 변경해야 할 때 훅 하나만 업데이트 하면 된다. 이는 코드를 유지보수하고 변경하기 쉽게 만든다.

3. 추상화를 통한 단순화: 컴포넌트들이 데이터 로직의 세부 사항을 몰라도 되기 때문에, 컴포넌트 코드가 더 간단하고 직관적이게 된다. 컴포넌트는 데이터를 가져오고 처리하는 방법에 대해 신경쓰지 않고도 데이터에 접근할 수 있다.

4. 컴포넌트의 역할 분리: 중간 계층인 커스텀 훅을 통해 데이터 로직이 분리되면 컴포넌트와 데이터 로직 간의 의존성이 줄어들게 되고 데이터 로직은 중간 계층인 커스텀 훅에 의해 처리되므로 컴포넌트는 UI와 관련된 코드에만 집중할 수 있다. 이는 코드의 모듈화와 관심사의 분리를 촉진하여 코드의 구조를 더 깔끔하고 유연하게 만든다.

의존성이 낮아지면 코드를 변경하거나 업데이트할 때 다른 부분에 미치는 영향이 줄어들게 된다. 또한 재사용성이 향상되어 코드를 더 쉽게 이해하고 유지 보수할 수 있습니다. 이러한 이점들은 코드의 가독성과 유지 보수성을 향상시키며, 전체적인 애플리케이션의 품질을 높이는 데 기여한다.

추상화❓

  • 복잡한 세부 내용을 숨기고 필수적인 부분만 노출하는 것을 의미한다. 데이터 로직을 추상화한다는 것은, 데이터를 가져오는 과정이나 상태를 업데이트 하는 방법 등의 세부 내용을 숨기고, 컴포넌트가 데이터에 대해 필요한 부분만 알 수 있도록 하는 것을 의미한다. 이렇게 함으로써 컴포넌트는 데이터 접근에 대해 더 간단하고 직관적으로 작성할 수 있다.

➡️ Custom Hook 생성하기

첫 번째 방식

import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Product, ProductDetail } from "../components/types/product";
import { apis } from "../shared/api";

interface ProductParams {
    finalId?: number;
    search?: string;
}

export default function useProducts({ finalId, search }: ProductParams = {}) {
    const queryClient = useQueryClient();

    const getProducts = useInfiniteQuery<Product[]>({
        queryKey: ['products'],
        queryFn: async ({ pageParam = 1 }) => { // pageParam의 형식을 직접 지정
            const response = await apis.getProduct(pageParam as number);
            return response.data.results;
        },
        getNextPageParam: (lastPage, pages): number | false => {
            const nextPage = pages.length + 1;
            return lastPage?.length === 0 ? false : nextPage;
        },
        initialPageParam: 1,
        staleTime: 60 * 1000,
    })

    const getProductList = useQuery({
        queryKey: ['allProduct'],
        queryFn: async () => {
            const promises = [];
            let page = 1;
            const response = await apis.getProduct(page);
            const count = response.data.count
            const totalPage = Math.ceil(count / 15)
            for (let page = 1; page <= totalPage; page++) {
                promises.push(apis.getProduct(page))
            }
            const res = await Promise.all(promises);
            const products = res.flatMap(response => response.data.results);
            console.log(products)
            return products;
        },
        staleTime: 60 * 1000,
    })

    const getProductItem = useQuery({
        queryKey: ['product', finalId],
        queryFn: async () => {
            const res = await apis.getOneProduct(finalId)
            return res.data
        },
        enabled: !!finalId, // finalId가 존재하는 경우에만 쿼리를 활성화
        // staleTime: 5 * 60 * 1000,
    })

    const getSearchProduct = useQuery({
        queryKey: ['searchProduct'],
        queryFn: async () => {
            const res = await apis.searchProduct(search as string)
            const list = res.data.results
            const filterList = list.filter((p: ProductDetail) => search && p.product_name.replace(" ", "").toLocaleLowerCase().includes(search.toLocaleLowerCase().replace(" ", "")))
            return filterList
        },
        enabled: !!search,
        staleTime: 5 * 60 * 1000,
    })

    const uploadProduct = useMutation({
        mutationFn: async (formData: FormData) => {
            const res = await apis.addProduct(formData)
            return res.data.results
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['products'] })
        },
        onError: (error) => {
            console.log("상품업로드에러", error)
            throw error;
        }
    })

    return {
        getProducts,
        getProductList,
        getProductItem,
        getSearchProduct,
        uploadProduct
    }
}

const {data:getProducts} = useProducts()

useProducts라는 커스텀 훅을 만들어서 products와 관련된 데이터를 가져오고, 생성하고, 삭제하고, 수정하는 쿼리 함수들을 모듈화시켰다. 그런데 이렇게 하니까 MainGrid라는 컴포넌트에서 useProducts의 getProducts 쿼리 함수를 호출해도 useProducts에서 return하고있는 다른 getProductList, getProductItem, getSearchProduct가 같이 호출되는 문제가 생겼다.
알아보니,커스텀 훅은 선언적으로 실행된다.

"선언적으로 실행된다"는 말은 컴포넌트 코드에서 어떤 작업을 명시적으로 실행하지 않아도 해당 작업이 자동으로 발생한다는 것을 의미한다.

따라서 useProducts커스텀 훅에서 선언된 쿼리함수들은 컴포넌트에서 커스텀 훅을 호출할 때 자동으로 실행되고 필요한 데이터를 가져오게 된다. 그렇기 때문에 useProducts 하나의 훅에 선언된 모든 쿼리 함수들에게 요청을 보내고 있는 것이다.

그렇기 때문에 보통 fetch 1개당 1개의 훅으로 분리해서 구현하지만, 이렇게 하면 애플리케이션 규모가 커질수록 파일 개수도 많아질 거라 생각이 들어서 생각해낸 게 두 번째 방법이다.👇

두 번째 방식

첫 번째 방식의 문제점을 해결하기 위해 찾아본 결과
https://tkdodo.eu/blog/the-query-options-api 이 tkdodo라는 블로그에서 '팩토리 패턴'이라는 디자인 패턴에 대해서 알게 되었고,

query-factory

const todoQueries = {
  all: () => ['todos'],
  lists: () => [...todoQueries.all(), 'list'],
  list: (filters: string) =>
    queryOptions({
      queryKey: [...todoQueries.lists(), filters],
      queryFn: () => fetchTodos(filters),
    }),
  details: () => [...todoQueries.all(), 'detail'],
  detail: (id: number) =>
    queryOptions({
      queryKey: [...todoQueries.details(), id],
      queryFn: () => fetchTodo(id),
      staleTime: 5000,
    }),
}

이 query-factory 형식의 패턴을 활용해보고자 했다.

query-factory 활용한 productQuery

import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { apis } from "../shared/api";
import { Product, ProductDetail, SellerProduct } from "../components/types/product";

export const productQuery = {
    useGetProducts: () =>
        useInfiniteQuery<Product[]>({
            queryKey: ['products'],
            queryFn: async ({ pageParam = 1 }) => {
                const response = await apis.getProduct(pageParam as number);
                return response.data.results;
            },
            getNextPageParam: (lastPage, pages): number | false => {
                const nextPage = pages.length + 1;
                return lastPage?.length === 0 ? false : nextPage;
            },
            initialPageParam: 1,
            staleTime: 60 * 1000,
        }),
    useGetProductList: () =>
        useQuery({
            queryKey: ['allProduct'],
            queryFn: async () => {
                const promises = [];
                let page = 1;
                const response = await apis.getProduct(page);
                const count = response.data.count
                const totalPage = Math.ceil(count / 15)
                for (let page = 1; page <= totalPage; page++) {
                    promises.push(apis.getProduct(page))
                }
                const res = await Promise.all(promises);
                const products = res.flatMap(response => response.data.results);
                console.log(products)
                return products;
            },
            staleTime: 60 * 1000,
        }),
    useGetProductItem: (finalId: number) =>
        useQuery({
            queryKey: ['product', finalId],
            queryFn: async () => {
                const res = await apis.getOneProduct(finalId)
                return res.data
            },
            staleTime: 5 * 60 * 1000,
        }),
    useGetSellerProducts: () =>
        useQuery<SellerProduct[]>({
            queryKey: ['sellerProducts'],
            queryFn: async () => {
                const res = await apis.getSellerProduct()
                return res.data.results
            }
        }),
    useGetSearchProduct: (search: string) =>
        useQuery({
            queryKey: ['searchProduct'],
            queryFn: async () => {
                const res = await apis.searchProduct(search)
                const list = res.data.results
                const filterList = list.filter((p: ProductDetail) => search && p.product_name.replace(" ", "").toLocaleLowerCase().includes(search.toLocaleLowerCase().replace(" ", "")))
                return filterList
            },
            enabled: !!search,
            staleTime: 5 * 60 * 1000,
        }),
    useUploadProduct: () => {
        const queryClient = useQueryClient();
        return useMutation({
            mutationFn: async (formData: FormData) => {
                const res = await apis.addProduct(formData)
                return res.data.results
            },
            onSuccess: () => {
                queryClient.invalidateQueries({ queryKey: ['products'] })
            },
            onError: (error) => {
                console.log("상품업로드에러", error)
                throw error;
            }
        })
    },
    useModifyProduct: () => {
        const queryClient = useQueryClient();
        return useMutation({
            mutationFn: async ({ id, data }: { id: number, data: FormData }) => {
                const res = await apis.modifyProduct(id, data);
                return res.data
            },
            onSuccess: () => {
                queryClient.invalidateQueries({ queryKey: ['products'] })
            },
            onError: (error) => {
                console.log("상품수정에러", error);
                throw error;
            }
        })
    },
    useDeleteProduct: () => {
        const queryClient = useQueryClient();
        return useMutation({
            mutationFn: async (productId: number) => {
                await apis.deleteProduct(productId)
            },
            onSuccess: () => {
                queryClient.invalidateQueries({ queryKey: ['sellerProducts'] })
            }
        })
    }
}

팩토리 패턴?

팩토리 패턴은 객체 생성을 캡슐화하여 클라이언트 코드가 객체의 생성 방식에 대해 알 필요 없이 원하는 객체를 생성할 수 있도록 하는 디자인 패턴이다.
이 코드에서도 각각의 팩토리 함수가 사용자에게 필요한 쿼리를 생성하고 반환하여 클라이언트 코드가 쿼리의 생성 방식에 대해 신경쓰지 않도록 한다.

코드 설명

여기에서는 productQuery 객체가 팩토리 역할을 한다. 이 객체는 여러 개의 팩토리 메서드(useGetProducts, useGetProductList, 등)를 포함하고 있다. 각 팩토리 메서드는 각각의 쿼리나 뮤테이션을 생성하고, 쿼리 키(queryKey)와 쿼리 함수(queryFn)를 사용하여 커스터마이징된 옵션을 제공하면서 특정 종류의 쿼리를 생성하고 반환한다.

팩토리 함수들을 사용하여 쿼리와 뮤테이션을 생성하고 관리함으로써 객체 생성 로직을 캡슐화하고 클라이언트 코드로부터 분리함으로써 유연성과 재사용성을 높일 수 있다.

예를 들어, useGetProducts 메서드는 useInfiniteQuery를 사용하여 무한 스크롤 기능이 있는 제품 목록을 가져오는 쿼리를 생성한다. 이 메서드는 클라이언트 코드가 각각의 쿼리를 생성하는 복잡한 로직을 알 필요 없이, 간단히 productQuery.useGetProducts()를 호출하여 제품 목록을 얻을 수 있도록 한다.

이러한 팩토리 패턴의 장점은 클라이언트는 단순히 필요한 함수를 호출하여 기능을 수행할 뿐, 함수의 내부 구현 세부 사항에 대해 신경 쓸 필요가 없습니다. 단순히 클라이언트가 필요한 팩토리 함수를 호출하여 기능을 얻는 방식으로 사용될 수 있다. 또한, 팩토리 패턴을 사용하면 나중에 함수의 내부 구현이 변경되어도 클라이언트 코드를 수정할 필요 없이 새로운 함수 유형이 추가되거나 기존 함수 유형이 변경되어도 클라이언트 코드를 수정하지 않아도 된다.

프로젝트에 적용

// MainGrid컴포넌트
import { useNavigate } from 'react-router-dom';
import styled from "styled-components";
import useInfiniteScroll from '../hooks/use-infinitescroll';
import LazyLoadingImage from './LazyLoading';
import PlaceholderImg from '../assets/images/placeholderImg.svg';
import { productQuery } from '../hooks/useProductQuery';

function MainGrid() {
    const navigate = useNavigate()
    const { data, hasNextPage, fetchNextPage } = productQuery.useGetProducts();
    const target = useInfiniteScroll({
        hasNextPage,
        fetchNextPage,
    })

    return (
        <Container>
            {
                data?.pages.flat().map((p, i) => {
                    return <div key={p?.product_id}>
                        <LazyLoadingImage
                            src={p?.image}
                            onError={(e: React.ChangeEvent<HTMLImageElement>) => {
                                e.target.onerror = null; // 에러 핸들러 무한 루프 방지
                                e.target.src = p.image // 이미지 로드 실패 시 p.image 사용
                                e.target.width = 380;
                                e.target.height = 380;
                            }}
                            alt={p?.product_name}
                            onClick={() => navigate(`/detail/${p?.product_id}`)}
                            placeholderImg={PlaceholderImg}
                        />
                        <p className='product-name'>{p?.store_name}</p>
                        <p className='product'>{p?.product_name}</p>
                        <span className='product-price'>{p?.price?.toLocaleString()}</span>
                        <span></span>
                    </div>
                })
            }
            {hasNextPage ? <div ref={target}></div> : null}
        </Container>
    )
}

MainGrid컴포넌트에 적용한 모습이다. MainGrid는 메인페이지인 홈페이지에 데이터를 보여주는 컴포넌트로 무한스크롤 기능을 수행하고 있다. productQuery의 useGetProducts는 useInfiniteQuery훅을 반환하고 있어서 useInfiniteQuery에서 반환하는 data와 hasNextPage, fetchNextPage를 사용해서 무한스크롤 기능을 수행할 수 있다.

const { data: product } = productQuery.useGetProductItem(finalId)

data에 특정 이름을 설정하고 싶으면 useQuery를 사용할 때 처럼 datae:product <- 이렇게 네이밍 시켜줄 수 있다.

커스텀 훅에서의 useMutation

// cartQueyr
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apis } from "../shared/api";
import { AddCart, ModifyCartQuantity } from "../components/types/product";

export const cartQuery = {
   useGetCart: () =>
        useQuery({
            queryKey: ['cartList'],
            queryFn: async () => {
                const res = await apis.getCart()
                return res.data.results
            },
            staleTime: 60 * 1000
        }),
    useDeleteCartItem: () => {
        const queryClient = useQueryClient();
        const { refetch: refetchCartList } = cartQuery.useGetCart();
        return useMutation({
            mutationFn: async (itemId: number) => {
                const res = await apis.deleteItem(itemId)
                return res.data
            },
            onSuccess: async () => {
                await queryClient.invalidateQueries({ queryKey: ['cartList'] });
                await refetchCartList();
            }
        })
    },

useMutation은 data를 반환하는 게 아니라 데이터를 생성하거나 삭제, 수정하기 때문에 cartQuery라는 팩토리 객체에서 useDeleteCartItem이라는 데이터 아이템을 삭제하는 useMutation훅을 return해준다. 그리고 사용할 때는 👇


// cartItem 삭제하기
const deleteCartItem = cartQuery.useDeleteCartItem()

deleteCartItem.mutate(itemId)
  1. useDeleteCartItem을 호출하여 얻은 결과를 deleteCartItem 변수에 저장, 이 deleteCartItem은 상품을 삭제하는 데 사용된다.
  2. deleteCartItem.mutate(itemId)는 상품 ID를 매개변수로 받아 mutationFn을 실행하여 해당 상품을 삭제한다.
  3. 삭제가 성공하면 onSuccess 콜백이 실행되어 'cartList' 쿼리를 무효화하고, 장바구니 목록을 업데이트한다. 또, 상품을 삭제한 후에 장바구니 목록을 다시 불러오기 위해 refetchCartList()를 호출합니다. 이를 통해 장바구니 목록이 삭제 후에 즉시 최신 정보로 업데이트된다.

출처

0개의 댓글