본문 바로가기

React

suspense

 

Suspense를 사용하면 컴포넌트가 렌더링되기 전까지 기다릴 수 있습니다.

 예시 : 두 컴포넌트가 데이터를 불러오는 비동기 API 호출을 기다립니다.

const resource = fetchProfileData();

function ProfilePage() {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <ProfileDetails />
      <Suspense fallback={<h1>Loading posts...</h1>}>
        <ProfileTimeline />
      </Suspense>
    </Suspense>
  );
}

function ProfileDetails() {
  // 비록 아직 불러오기가 완료되지 않았겠지만, 사용자 정보 읽기를 시도합니다
  const user = resource.user.read();
  return <h1>{user.name}</h1>;
}

function ProfileTimeline() {
  // 비록 아직 불러오기가 완료되지 않았겠지만, 게시글 읽기를 시도합니다
  const posts = resource.posts.read();
  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.text}</li>
      ))}
    </ul>
  );
   
 
 
 

 

사용예

 

<Suspense fallback={(<div>Loading...</div>)}>
      <NavBar />
      <div style={{ paddingTop: '69px', minHeight: 'calc(100vh - 80px)' }}>


        <Switch>
          <Route exact path="/" component={Auth(LandingPage, null)} />
          <Route exact path="/login" component={Auth(LoginPage, false)} />
          <Route exact path="/register" component={Auth(RegisterPage, false)} />
          <Route exact path="/movie/:movieId" component={Auth(MovieDetail, null)} />


          <Route exact path="/favorite" component={Auth(FavoritePage, true)} /> 
        </Switch>
      </div>
      <Footer />
    </Suspense>

 

 

 

 

 

 

 

'React' 카테고리의 다른 글

React Router v6 업데이트  (0) 2021.12.26
useRef  (0) 2021.12.25
환경변수 설정,사용법  (0) 2021.12.23
Virtual DOM [리액트를 쓰는 이유?]  (0) 2021.11.22
HOC(Higher-order Component)  (0) 2021.11.08