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

Frontend Dev/๐Ÿฅ ์ฝ”๋“œ์Šคํ…Œ์ด์ธ  FE ๋ถ€ํŠธ์บ ํ”„

Section4 Unit3 [React] ์‹ฌํ™” - ์ฝ”๋“œ๋ถ„ํ• ๊ณผ React.lazy() & Suspense

๋ฐ˜์‘ํ˜•


Section4 Unit3 [React] ์‹ฌํ™” - Code Spliting, React.lazy() & Suspense

 

๐Ÿ“Œ Chapter3. React์˜ ์ฃผ๋ชฉํ•ด์•ผ ํ•  ๊ธฐ๋Šฅ

 ์ฃผ๋ชฉํ•ด์•ผ ํ•  ๊ธฐ๋Šฅ์ธ๊ฐ€? ์˜ค๋Š˜ QnA ์„ธ์…˜์—์„œ ์™ธ๋ถ€ ๊ฐ•์‚ฌ๋‹˜์ด Suspense๋Š” ์ž˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ํ•˜์‹œ๊ธด ํ–ˆ๋‹ค๋งŒ...๐Ÿ˜

 ์—ฌํŠผ, ๋ฌด๊ฑฐ์›Œ์ง„ ๋ฆฌ์•กํŠธ ์•ฑ์˜ ์„ฑ๋Šฅ์„ ์ตœ์ ํ™”ํ•˜๋Š” ๊ฒƒ์€ ์ค‘์š”ํ•œ ์ผ์ž„์€ ํ‹€๋ฆผ์—†๋‹ค. ์ด ๋ถ€๋ถ„์€ ์ข€ ๋” ๊ณต๋ถ€๋ฅผ ํ•ด๋ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์ง€๋งŒ, ์šฐ์„  ๋ฐฐ์šด ๋‚ด์šฉ๋“ค๋งŒ ๊ฐ„๋‹จํžˆ ์ •๋ฆฌํ•ด๋ณด์ž๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค. 

 

React๋Š” SPA(Single-Page-Application)์ด๋ฏ€๋กœ ํ•œ ๋ฒˆ์— ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ์ปดํฌ๋„ŒํŠธ๊นŒ์ง€ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค. React.lazy ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋™์ ์œผ๋กœ import๋ฅผ ํ•  ์ˆ˜ ์žˆ๊ณ , ์ด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ดˆ๊ธฐ ๋ Œ๋”๋ง ์ง€์—ฐ์‹œ๊ฐ„์„ ์–ด๋Š ์ •๋„ ์ค„์ผ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

import Component from './Component';

/* React.lazy๋กœ dynamic import๋ฅผ ๊ฐ์Œ‰๋‹ˆ๋‹ค. */
const Component = React.lazy(() => import('./Component'));

React.lazy๋กœ ๊ฐ์‹ผ ์ปดํฌ๋„ŒํŠธ๋Š” ๋‹จ๋…์œผ๋กœ ์“ฐ์ผ ์ˆ˜๋Š” ์—†๊ณ , React.suspense ์ปดํฌ๋„ŒํŠธ์˜ ํ•˜์œ„์—์„œ ๋ Œ๋”๋ง์„ ํ•ด์•ผ ํ•œ๋‹ค.

 

import { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Suspense>
  </Router>
);

 

 ๋ผ์šฐํ„ฐ๊ฐ€ ๋ถ„๊ธฐ๋˜๋Š” ์ปดํฌ๋„ŒํŠธ์—์„œ ๊ฐ ์ปดํฌ๋„ŒํŠธ์— React.lazy๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ importํ•˜๊ณ , Route ์ปดํฌ๋„ŒํŠธ๋“ค์„ Suspense๋กœ ๊ฐ์‹ผ ํ›„ ๋กœ๋”ฉ ํ™”๋ฉด์œผ๋กœ ์‚ฌ์šฉํ•  ์ปดํฌ๋„ŒํŠธ๋ฅผ fallback ์†์„ฑ์œผ๋กœ ์„ค์ •ํ•ด ์ฃผ๋ฉด ๋œ๋‹ค. ์ดˆ๊ธฐ ๋ Œ๋”๋ง ์‹œ๊ฐ„์ด ์ค„์–ด๋“œ๋Š” ๋ถ„๋ช…ํ•œ ์žฅ์ ์ด ์žˆ์œผ๋‚˜ ํŽ˜์ด์ง€๋ฅผ ์ด๋™ํ•˜๋Š” ๊ณผ์ •๋งˆ๋‹ค ๋กœ๋”ฉ ํ™”๋ฉด์ด ๋ณด์ด๊ธฐ ๋•Œ๋ฌธ์— ์„œ๋น„์Šค์— ๋”ฐ๋ผ์„œ ์ ์šฉ ์—ฌ๋ถ€๋ฅผ ๊ฒฐ์ •ํ•ด์•ผ ํ•œ๋‹ค.

 

 

๐Ÿ‘๐Ÿป ๋ฆฌ์•กํŠธ ๊ณต์‹๋ฌธ์„œ๋ฅผ ๋ณด๋‹ˆ ์„ค๋ช…๊ณผ ๊ณผ์ •์ด ์ž์„ธํžˆ ๋‚˜์™€ ์žˆ์–ด์„œ ์ดํ•ดํ•˜๋Š”๋ฐ ๋„์›€์ด ๋˜์—ˆ๋‹ค.

 

lazy – React

The library for web and native user interfaces

ko.react.dev


๐ŸŒ™  ์˜ค๋Š˜์˜ ํšŒ๊ณ 

 ๋งค์ผ ์งง๊ฒŒ๋ผ๋„ ํ•˜๋ฃจ๋ฅผ ๋งˆ๊ฐํ•œ ์†Œ๊ฐ์„ ์“ฐ๋ ค๊ณ  ํ•˜๋Š”๋ฐ, ์š”์ฆ˜์€ ํ•ด์•ผํ•  ๊ณต๋ถ€๊ฐ€ ๋” ๋งŽ์•„์ง„ ๊ฒƒ ๊ฐ™์•„์„œ ํšŒ๊ณ ์“ธ ์‹œ๊ฐ„๋„ ์—†๋Š” ๊ฒƒ ๊ฐ™๋‹ค. ์ •์‹ ์—†์ด ํ•˜๋‹ค๋ณด๋ฉด ์–ด๋Š๋ง ์ƒˆ๋ฒฝ..๐Ÿซ  ๋ฆฌ์•กํŠธ ์‹ฌํ™”์— ๋“ค์–ด๊ฐ€๋‹ˆ ๋” ์žฌ๋ฏธ์žˆ๊ธฐ๋Š” ํ•œ๋ฐ, ์ต์ˆ™์น˜ ์•Š์€ ๊ฐœ๋…์ด๋ผ ์ ์‘ํ•˜๊ณ  ํ™œ์šฉํ•  ์‹œ๊ฐ„์ด ํ•„์š”ํ•œ ๊ฒƒ ๊ฐ™๋‹ค. ์†”๋กœ ํ”„๋กœ์ ํŠธ๋„ ๋งˆ๋ฌด๋ฆฌํ•˜๋ ค ํ–ˆ๋Š”๋ฐ, ๋‹ค์‹œ ๊ฑด๋“œ๋ฆฌ์ง€๋„ ๋ชปํ•˜๊ณ  ์žˆ๋Š” ์ค‘์ด๋‹ค. ์ฃผ๋ง๋™์•ˆ ๊ฐ€๋Šฅํ• ๊นŒ? ๋ฒŒ์จ ์ˆ˜์š”์ผ์ด ์ง€๋‚˜๊ฐ€๋‹ค๋‹ˆ.

๋ฐ˜์‘ํ˜•