React의 Suspense 기능이 추가된 이래로, React-Query와 같은 비동기 상태 처리 라이브러리는 suspense 기능을 지원하게 되었다.
그리고 이번에 카카오페이 기술 블로그의 글을 보았는데, 여기에 더해서 react-error-boundary 라이브러리로 에러처리까지 한 번에 하는 것이 매우매우매우 인상적이었다.
🍓 사실, 에러 처리나 로딩 관련 로직은 필요하면서도 반복적인 코드가 계속 들어가게 만드는 문제가 있기에 이 방법이 더 가치있는 것 같다.
그래서, 이번에 이 세가지 기술들을 직접 사용해보고 기록을 남기기로 하였다.
기본적인 구조는 다음과 같다.
import styles from "./page.module.css";
import React, { Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";
import Loading from "@/components/Loading";
import Error from "@/components/Error";
export default function Home({ children }: { children: React.ReactNode }) {
return (
<ErrorBoundary FallbackComponent={Error}>
<Suspense fallback={<Loading />}>
{children}
</Suspense>
</ErrorBoundary>
);
}
에러가 발생하면, ErrorBoundary의 FallbackComponent 속성에 연결된 컴포넌트가 렌더링된다.
만약, React-Query에서 로딩이 일어나면, Loading 컴포넌트를 렌더링한다.
에러 컴포넌트를 살펴보면 다음과 같다.
import { FallbackProps } from "react-error-boundary";
export default function Error({ error, resetErrorBoundary }: FallbackProps) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
</div>
);
}
error와 resetErrorBoundary, 두 가지 props를 가지는데 error 객체에 에러 메세지가 담겨지고 resetErrorBoundary 함수로 ErrorBoundary를 리셋할 수 있다.
Loading 컴포넌트는 서버와 통신하는 과정에서 사용자에게 로딩 알림을 보여줄 수 있다.
import { useQuery } from "@tanstack/react-query";
import axios from "@/utils/api";
import { Post } from "@/types/postType";
interface DataPosts {
message: string;
data: Post[];
}
export const useGetAllPosts = () => {
const { data } = useQuery<DataPosts>({
queryKey: ["all_posts"],
queryFn: () => axios.get("/board/all").then((res) => res.data),
suspense: true,
});
return { data };
};
react-query의 suspense 옵션을 true로 하면 isLoading이 true일 때, Suspense fallback이 랜더링된다.
Suspense fallback에는 로딩 컴포넌트, 스켈레톤 컴포넌트등을 연결할 수 있다.
https://www.npmjs.com/package/react-error-boundary
react-error-boundary
Simple reusable React error boundary component. Latest version: 4.0.10, last published: a month ago. Start using react-error-boundary in your project by running `npm i react-error-boundary`. There are 812 other projects in the npm registry using react-erro
www.npmjs.com
'React' 카테고리의 다른 글
React JSX의 List Rendering에서 key값 설정하기 (.map) (0) | 2023.09.23 |
---|---|
Server Component에서 Css-in-JS 라이브러리 사용하기 (feat. panda-css) (0) | 2023.08.18 |
useReducer의 장점 알아보기 (vs useState) (0) | 2023.07.15 |
React 빌드 후 정적 파일 서버에 올리기 (404 Error 해결) (0) | 2023.07.01 |
React에서 상태관리 툴 zustand 사용하기 (0) | 2023.06.14 |