컴포넌트를 어떻게 구조화 시키나
컴포넌트를 어떻게 구조화 시키나
기능 또는 경로 별로 그룹화 합니다
파일 및 디렉토리 구조
컴포넌트 구조화의 첫 단계는 파일 및 디렉토리 구조를 잘 설정하는 것입니다. 일반적으로 다음과 같은 구조를 사용할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
src/
components/
Header/
Header.js
Header.css
Footer/
Footer.js
Footer.css
Button/
Button.js
Button.css
pages/
Home/
Home.js
Home.css
About/
About.js
About.css
App.js
index.js
폴더 별로 컴포넌트 분리
컴포넌트를 폴더 별로 분리하면, 관련된 파일들을 한 곳에 모아 관리하기 쉽습니다. 각 컴포넌트 폴더는 컴포넌트의 JavaScript 파일과 스타일링 파일(CSS, SCSS 등)을 포함할 수 있습니다.
재사용 가능한 컴포넌트 만들기
컴포넌트를 재사용 가능하게 만드는 것이 중요합니다. 컴포넌트가 특정 페이지나 기능에만 국한되지 않도록 설계하세요. 예를 들어, 버튼 컴포넌트는 다양한 크기, 색상, 기능을 지원하도록 만들 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
// Button.js
import React from 'react';
import './Button.css';
const Button = ({ type = 'button', onClick, children, className }) => (
<button type={type} onClick={onClick} className={`button ${className}`}>
{children}
</button>
);
export default Button;
컨테이너와 프레젠테이션 컴포넌트 분리
컨테이너 컴포넌트는 애플리케이션의 상태와 로직을 관리하고, 프레젠테이션 컴포넌트는 UI를 렌더링하는 데 집중합니다. 이렇게 분리하면 컴포넌트를 보다 명확하게 이해하고 유지보수하기 쉬워집니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ContainerComponent.js
import React, { useState, useEffect } from 'react';
import PresentationComponent from './PresentationComponent';
const ContainerComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
// 데이터 가져오기 로직
setData(fetchedData);
}, []);
return <PresentationComponent data={data} />;
};
export default ContainerComponent;
1
2
3
4
5
6
7
8
9
10
// PresentationComponent.js
import React from 'react';
const PresentationComponent = ({ data }) => (
<div>
{data ? <p>{data}</p> : <p>Loading...</p>}
</div>
);
export default PresentationComponent;
스타일링 방법 통일
CSS-in-JS, CSS Modules, Sass 등 다양한 스타일링 방법이 있습니다. 팀 내에서 하나의 스타일링 방법을 통일하여 사용하면 스타일 관리가 편리해집니다. 예를 들어, CSS Modules를 사용하는 경우:
1
2
3
4
5
6
7
8
9
10
11
12
// Button.module.css
.button {
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
}
.primary {
background-color: blue;
color: white;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Button.js
import React from 'react';
import styles from './Button.module.css';
const Button = ({ type = 'button', onClick, children, variant = 'primary' }) => (
<button
type={type}
onClick={onClick}
className={`${styles.button} ${styles[variant]}`}
>
{children}
</button>
);
export default Button;
상태 관리
전역 상태 관리가 필요한 경우, Redux, Context API, MobX 등 상태 관리 라이브러리를 사용하여 상태를 체계적으로 관리합니다. 상태 관리 로직을 별도의 디렉토리에 두어 컴포넌트와 분리합니다.
코드 스플리팅과 다이나믹 임포트
코드 스플리팅을 통해 초기 로딩 시간을 줄일 수 있습니다. 다이나믹 임포트를 사용하면 필요한 시점에만 컴포넌트를 로드할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
// LazyLoadedComponent.js
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./ComponentToLoad'));
const LazyLoadedComponent = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
export default LazyLoadedComponent;
This post is licensed under CC BY 4.0 by the author.
