Suspense 란?
Suspense는 리액트에서 제공하는 컴포넌트로 일부 데이터 또는 리소스가 불리울때까지 로딩 상태를 처리하고 대체 컨텐츠를 표시할 수 있다.
주로 동적 import와 비동기 데이터 Fetching을 처리할 때 사용된다.
그렇다면 왜 사용할까?
- 비동기 데이터나 컴포넌트가 로드될 때, 로딩 상태를 직접 관리하지 않아도 된다.
- 사용자에게 더 나은 로딩 경험을 제공한다.
- 코드 분할과 비동기 데이터 처리를 쉽게 구현할 수 있다.
Suspense의 주요 특징
- Lazy Loading: 컴포넌트를 비동기적으로 로드할 때 사용한다.
- 비동기 데이터 Fetching: React Server Components 및 React Concurrent Features와 함께 사용
비동기 데이터 Fetching과 Suspense 사용 예시
import React, { Suspense } from 'react';
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Data Loaded!"), 2000);
});
}
function DataComponent() {
const data = fetchData();
return <div>{data}</div>;
}
export default function App() {
return (
<Suspense fallback={<div>Loading data...</div>}>
<DataComponent />
</Suspense>
);
}
DataComponent
에서 데이터를 로드할 때,Suspense
를 통해 로딩 UI를 표시한다.- 비동기 데이터 로딩이 완료되면,
DataComponent
가 렌더링된다.