Suspense
React의 Suspense를 확장하여 클라이언트 전용 컴포넌트를 지원하는 컴포넌트입니다. 데이터 로딩, 코드 스플리팅, 클라이언트 사이드 렌더링 등을 처리할 수 있습니다.
Props
이름 | 타입 | 설명 | 기본값 |
---|---|---|---|
children | ReactNode | 렌더링할 자식 컴포넌트 | - |
fallback | ReactNode | 로딩 중일 때 렌더링할 컴포넌트 | - |
clientOnly | boolean | 클라이언트에서만 렌더링할지 여부 | false |
Usage
import { Suspense } from '@teamsparta/react';
function Example() {
return (
<Suspense fallback={<div>로딩 중...</div>}>
<SomeComponent />
</Suspense>
);
}
Example
기본 사용법
function BasicExample() {
return (
<Suspense fallback={<div>로딩 중...</div>}>
<LazyComponent />
</Suspense>
);
}
Tanstack Query와 함께 사용
import { useSuspenseQuery } from '@tanstack/react-query';
interface Post {
id: number;
title: string;
content: string;
}
async function fetchPost(id: number): Promise<Post> {
const response = await fetch(`/api/posts/${id}`);
return response.json();
}
function PostComponent({ id }: { id: number }) {
const { data } = useSuspenseQuery({
queryKey: ['post', id],
queryFn: () => fetchPost(id),
});
return (
<div>
<h1>{data.title}</h1>
<p>{data.content}</p>
</div>
);
}
function PostPage() {
return (
<Suspense fallback={<div>포스트를 불러오는 중...</div>}>
<PostComponent id={1} />
</Suspense>
);
}
클라이언트 전용 컴포넌트
function ClientOnlyExample() {
return (
<Suspense clientOnly fallback={<div>로딩 중...</div>}>
<BrowserAPIComponent />
</Suspense>
);
}
중첩 사용
function NestedExample() {
return (
<Suspense fallback={<div>외부 로딩...</div>}>
<OuterComponent>
<Suspense fallback={<div>내부 로딩...</div>}>
<InnerComponent />
</Suspense>
</OuterComponent>
</Suspense>
);
}
주의사항
clientOnly
가true
이면 서버에서는 항상fallback
을 렌더링합니다.- 중첩된 Suspense는 독립적으로 동작합니다.
fallback
은 반드시 제공해야 합니다.- React의 Suspense 규칙이 모두 적용됩니다.
- SSR 환경에서는
clientOnly
옵션을 신중하게 사용해야 합니다.