๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ปWEB FrontEnd/ํ”„๋ ˆ์ž„์›Œํฌ React

์„ฑ๋Šฅ๊ฐœ์„ (1) - lazy import

lazy import

- ๋ฆฌ์•กํŠธ ์‚ฌ์ดํŠธ๋“ค์€ ์ฒซ ํŽ˜์ด์ง€ ๋กœ๋”ฉ์†๋„๊ฐ€ ๋งค์šฐ ๋Š๋ฆด ์ˆ˜ ์žˆ๋Š”๋ฐ ๊ทธ๊ฒŒ ์‹ซ๋‹ค๋ฉด js ํŒŒ์ผ์„ ์ž˜๊ฒŒ ์ชผ๊ฐœ๋ฉด ๋œ๋‹ค.

- ์ชผ๊ฐœ๋Š” ๋ฐฉ๋ฒ•์€ import ๋ฌธ๋ฒ•์„ ์•ฝ๊ฐ„ ๊ณ ์น˜๋ฉด ๋˜๋Š”๋ฐ ์ง€๊ธˆ ํŽ˜์ด์ง€์—์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์žˆ๋Š” ์ปดํฌ๋„ŒํŠธ๋“ค์€ lazy import ํ•ด๋†“์œผ๋ฉด ์ข‹๋‹ค.

- ๋‹จ์  :  lazy๋ฌธ๋ฒ•์œผ๋กœ importํ•œ ์ปดํฌ๋„ŒํŠธ๋“ค์„ ๋กœ๋“œํ•  ๋•Œ๋Š” ๋กœ๋”ฉ์‹œ๊ฐ„์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค.

 

1. lazy()

(App.js)

import Detail from './routes/Detail.js'
import Cart from './routes/Cart.js'

↓↓↓

 

(App.js)
import {lazy, Suspense, useEffect, useState} from 'react'

const Detail = lazy( () => import('./routes/Detail.js') )
const Cart = lazy( () => import('./routes/Cart.js') )

 

lazy ๋ฌธ๋ฒ•์œผ๋กœ๋„ ๋˜‘๊ฐ™์ด import๊ฐ€ ๊ฐ€๋Šฅํ•œ๋ฐ ์ด ๊ฒฝ์šฐ์—”

"Detail ์ปดํฌ๋„ŒํŠธ๊ฐ€ ํ•„์š”ํ•ด์ง€๋ฉด import ํ•ด์ฃผ์„ธ์š”" ๋ผ๋Š” ๋œป์ด ๋œ๋‹ค. 

๊ทธ๋ฆฌ๊ณ  ์ด๋ ‡๊ฒŒ ํ•ด๋†“์œผ๋ฉด Detail ์ปดํฌ๋„ŒํŠธ ๋‚ด์šฉ์„ ๋‹ค๋ฅธ js ํŒŒ์ผ๋กœ ์ชผ๊ฐœ์ค๋‹ˆ๋‹ค.

๊ทธ๋ž˜์„œ ์ฒซ ํŽ˜์ด์ง€ ๋กœ๋”ฉ์†๋„๋ฅผ ํ–ฅ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค.

 

2. Suspense

lazy ์‚ฌ์šฉํ•˜๋ฉด ๋‹น์—ฐํžˆ Detail ์ปดํฌ๋„ŒํŠธ ๋กœ๋“œ๊นŒ์ง€ ์ง€์—ฐ์‹œ๊ฐ„์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ทธ๋Ÿด ๋•

1. Suspense ๋ผ๋Š”๊ฑฐ import ํ•ด์˜ค๊ณ 

2. Detail ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ์‹ธ๋ฉด

Detail ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋กœ๋”ฉ์ค‘์ผ ๋•Œ ๋Œ€์‹  ๋ณด์—ฌ์ค„ html ์ž‘์„ฑ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค. 

<Suspense fallback={ <div>๋กœ๋”ฉ์ค‘์ž„</div> }>
  <Detail shoes={shoes} />
</Suspense>

๊ท€์ฐฎ์œผ๋ฉด <Suspense> ์ด๊ฑธ๋กœ <Routes> ์ „๋ถ€ ๊ฐ์‹ธ๋„ ๋œ๋‹ค.