⭐FE

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

devWarrior 2024. 1. 24. 22:15

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