[React] Suspense

DONNIE·2023년 10월 18일
0

React

목록 보기
23/26

Why Suspense ?

A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.

플젝할 때 마다 위 에러를 계속 봤는데, product 모드에선 발생하지 않아 방치했는데, 이젠 안되겟음

Suspense

  • 리액트는 선언형 프로그래밍을 지향함

  • 비동기 데이터 통신시, 데이터 상태에 따라 컴포넌트를 랜더링 하는 건 명령형 프로그래밍 방식임

  • 컴포넌트의 랜더링을 어떤 작업이 끝날때까지 잠시 중단시키고 다른 컴포넌트를 먼저 랜더링해줌

  • 비동기 데이터 통신 작업에서 중요

  • 컴포넌트가 읽어야하는 데이터가 준비되지않은 상태를 리액트에게 알려주는 매커니즘

  • React.lazy()로 컴포넌트를 읽어오면 route 부분에서 Suspense를 추가하고, 컴포넌트 로딩 전 상태를 fallback 에 전달하면 됨

  • App.js

.
.
.
(생략)

return (
<Suspense fallback={<Loading />}>
      <BrowserRouter>
      <Routes>
        {
          routes.map((each, index) => {
            return (
            <Route
              key={`route-${index}`}
              path={each.path}
              Component={each.element}
              />
            )
          })
        }
      </Routes>
    </BrowserRouter>
    </Suspense>
)

근데 너무 짧아서 loading spinner가 잘 보이지도 않아서 그냥 텍스트로 바꿈

<Suspense fallback='loading...'>
.
.
.
생략
.
.
.
</Suspense>
profile
후론트엔드 개발자

0개의 댓글