React에서 비동기 작업을 관리하기 위한 기능이다. 이를 이용하여 각 컴포넌트가 데이터를 받아 올 때까지 사용자에게 로딩화면을 제공해 줄 수도 있다.
import { Suspense, useState, useEffect } from 'react';
import Components from './Components';
function App() {
const [data, setData] = useState(null)
useEffect(() => {
fetch("api")
.then((response) => response.json())
.then((data) => setData(data));
},[])
return(
<div className='App'>
<h2>Suspense</h2>
<Suspense fallback={<div>Loading...</div>}> //fallback 함수로 Loading화면이나 문구를 제공
<Components data={data}/>
</Suspense>
</div>
)
}
🖐️ React.lazy란?
React에서 컴포넌트 파일을 최상단에 import로 정희하고 동적으로 불러오기를 사용하면 에러가 발생한다. 따라서 컴포넌트를 동적으로 불러오기 위해서는 React.lazy()를 사용해야 한다.
🖐️ React.lazy를 사용해야 하는 이유
일반적으로 규모가 큰 App은 많은 요소, 라이브러리 등으로 구성되기 때문에 사용자가 첫 페이지를 로드하는 즉시 한꺼번에 JS 번들이 사용자에게 전송되기 때문에 페이지 성능에 상당한 영향을 끼칠 수 있다. 따라서 React.lazy()를 사용함으로 요소들을 청크로 분리하여 제공할 수 있도록 도와준다.
🖐️ React.lazy 사용법
import { Suspense, useState, useEffect } from 'react';
// import Components from './Components';
function App() {
const [data, setData] = useState(null)
useEffect(() => {
fetch("api")
.then((response) => response.json())
.then((data) => setData(data));
},[])
const Componets = React.lazy(() => import('./Components)); //사용하고자 하는 컴포넌트를 변수로 만들어 정의한다.
return(
<div className='App'>
<h2>Suspense</h2>
<Suspense fallback={<div>Loading...</div>}> //fallback 함수로 Loading화면이나 문구를 제공
<Components data={data}/>
</Suspense>
</div>
)
}