Suspense는 리액트에서 기본적으로 제공하는 컴포넌트로, 자식 컴포넌트가 로딩이 될 때 까지 fallback을 보여줄 수 있다.
즉, 기존에 사용하던 isLoading 상태를 이용한 패턴을 더 간단하게 사용할 수 있게 해주는 컴포넌트이다.
Suspense 내부에 들어가는 Content 컴포넌트이다.
import { useEffect, useState } from "react";
let tmp = "";
const getData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
tmp = "Hello Mr.Park";
resolve(true);
}, 3000);
});
};
const Content = () => {
const [data, setData] = useState(tmp);
if (!data) {
throw getData();
}
return <div>LOADED {data}</div>;
};
export default Content;
실제 Suspense가 사용되는 부분이다.
import { lazy, Suspense } from "react";
import Content from "./Content";
function Loading() {
return (
<div>
<span role="img" aria-label="load">
🍘🍻🍪🍰🍧
</span>
is Loading
</div>
);
}
export default function TestSuspense() {
return (
<Suspense fallback={<Loading />}>
<Content />
</Suspense>
);
}
Suspense를 제대로 사용하기 위해서는 Promise의 설정이 필요하다.
위의 예시처럼, throw를 통해서 Promise를 확인해주어야 하는 부분이 필요하다.
또한 lazy를 사용했을 때 역시 fallback을 보여줄 수 있다.
import React, { lazy } from 'react';
const Content = lazy(() => import("./Content"));
Suspense를 잘 사용하면, 리액트 컴포넌트에서 비동기 작업이 일어났을 때 해당 처리가 완료될 때 까지 fallback으로 화면을 처리할 수 있다.
개인적인 생각으로 이는 React Query와 함께 사용하였을 때 활용도가 극대화된다.
비동기 상태 처리를 위한 훌륭한 솔루션인 React Query는 Suspense에 대한 옵션을 가지고 있다.
이 옵션을 키면, React Query의 비동기 처리가 일어날 때 마다, isLoading이 true라면 자동으로 fallback이 처리될 것이다.
🍉 queryClient에서 전역으로 suspense를 설정할 수도 있지만, 개별적인 useQuery마다 suspense를 설정할 수도 있다.
https://react.dev/reference/react/Suspense
<Suspense> – React
The library for web and native user interfaces
react.dev
https://tanstack.com/query/v4/docs/react/guides/suspense#resetting-error-boundaries
Suspense | TanStack Query Docs
NOTE: Suspense mode for React Query is experimental, same as Suspense for data fetching itself. These APIs WILL change and should not be used in production unless you lock both your React and React Query versions to patch-level versions that are compatible
tanstack.com
'React' 카테고리의 다른 글
useEffect의 life cycle (0) | 2023.05.21 |
---|---|
Vite를 사용하여 React 프로젝트 시작하기 (0) | 2023.05.15 |
tailwindcss 중복 클래스 줄이기 (@layer, @apply) (0) | 2023.05.06 |
React 정리 (0) | 2023.04.29 |
유지보수하기 좋은 React 코드를 작성하는 방법에 대한 고찰 (0) | 2023.04.13 |