react lazy loading 처리 방법 ( suspense와 lazy 이용 )

2024. 1. 24. 22:15·⭐FE

react lazy loading 처리 방법

오늘 다루고자 하는 내용은 react lazy loading 처리 방법이다.

코드를 먼저 보면서 이해 해 보자  ( 하단 코드는 의도를 전달하기 위한 수도 코드임을 참고 부탁드립니다. )

// ParentComponent.jsx 
import { lazy, suspense } from '... source' 
import {LoadingUI} from '...source'


const ChillComponent = lazy(() => import('./ChildComponent'))
const ParentComponent=()=>{
	return (   
        <suspense fallback={LoadingUI}>
            <ChildComponent/>
        </suspense>
    )
}


// ChildComponent.jsx
export const ChildComponent =()=>{
	const data = new Promise((resolce,reject)=>{
    	setTimeout(()=>{
        	resolve('안녕하세요')
        },3000)
    
    })
    
    return (
    	{data}
    ) 
}

 

위 코드에서 ChildComponent는 3초 뒤에 '안녕하세요' 를 렌더 한다. 그 전까지는 LoadingUI 가 대신 노출된다. 

 

<suspense> 로 감싸진 component 내부에 비동기를 감지하고 Promise pending이 끝나기 전까지는 그 대신 fallback 으로 지정된 컴포넌트를 렌더링 하는 것이다. 

 

lazy import 는 컴포넌트를 동적으로 load하며 일반적인 컴포넌트와 다르게 첫 렌더링이 시작되기 전 까지는 해당 코드가 load 되지 않는다고 한다. 

 

공식 홈페이지를 위와 같이 lazy import와 suspense를 함께 일반적으로 사용하기를 권장한다.

 

참고

https://react.dev/reference/react/Suspense

 

<Suspense> – React

The library for web and native user interfaces

react.dev

https://react.dev/reference/react/lazy

 

lazy – React

The library for web and native user interfaces

react.dev

 

'⭐FE' 카테고리의 다른 글

[JS] 미리보기 이미지 구현하기 ( FileReader, FileReader.readAsDataURL() 이용 )  (0) 2024.05.15
Yarn berry Package Manager 설치방법  (0) 2024.02.12
project별로 prettier 설정하기 ( vscode )  (0) 2023.12.18
예외 처리 방법 ( throw, Error 이용 )  (1) 2023.11.30
http request 의 content-type이해하기  (0) 2023.11.28
'⭐FE' 카테고리의 다른 글
  • [JS] 미리보기 이미지 구현하기 ( FileReader, FileReader.readAsDataURL() 이용 )
  • Yarn berry Package Manager 설치방법
  • project별로 prettier 설정하기 ( vscode )
  • 예외 처리 방법 ( throw, Error 이용 )
devWarrior
devWarrior
  • devWarrior
    devWarrior
    devWarrior
  • 전체
    오늘
    어제
    • 🧩Dev (263)
      • ⭐FE (34)
      • 🔒Algorithm (155)
      • ➕Etc. (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    티스토리챌린지
    실버4
    자스
    프론트엔드
    구현
    그리디
    node.js
    코테
    dp
    Lv2
    자바스크립트
    FE
    javascript
    실버2
    Algorithm
    백준
    DFS
    js
    프로그래머스
    BFS
    leetcode
    코딩테스트
    Easy
    실버3
    골드5
    nodejs
    오블완
    실버1
    알고리즘
    react
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
devWarrior
react lazy loading 처리 방법 ( suspense와 lazy 이용 )
상단으로

티스토리툴바