컴포넌트 추출이란 복잡한 컴포넌트를 작은 컴포넌트로 나누어 코드의 가독성과 재사용성을 높이는 작업이다.
다음은 댓글(Comment)을 렌더링하는 컴포넌트이다:
function Comment(props) {
return (
<div className="comment">
<div className="user-info">
<img className="avatar" src={props.author.avatarUrl} alt={props.author.name} />
<div className="user-info-name">{props.author.name}</div>
</div>
<div className="comment-text">{props.text}</div>
<div className="comment-data">{formatDate(props.date)}</div>
</div>
);
}
위 코드에서:
1. 유저 정보(이미지, 이름)을 담당하는 부분과,
2. 댓글 내용을 담당하는 부분을 각각 컴포넌트로 추출할 수 있다.
기존 코드:
<img className="avatar" src={props.author.avatarUrl} alt={props.author.name} />
추출된 Avatar 컴포넌트:
function Avatar(props) {
return <img className="avatar" src={props.user.avatarUrl} alt={props.user.name} />;
}
추출 이유:
추출 후 적용:
function Comment(props) {
return (
<div className="comment">
<div className="user-info">
<Avatar user={props.author} />
<div className="user-info-name">{props.author.name}</div>
</div>
<div className="comment-text">{props.text}</div>
<div className="comment-date">{formatDate(props.date)}</div>
</div>
);
}
기존 코드:
<div className="user-info">
<Avatar user={props.author} />
<div className="user-info-name">{props.author.name}</div>
</div>
추출된 UserInfo 컴포넌트:
function UserInfo(props) {
return (
<div className="user-info">
<Avatar user={props.user} />
<div className="user-info-name">{props.user.name}</div>
</div>
);
}
추출 이유:
추출 후 적용:
function Comment(props) {
return (
<div className="comment">
<UserInfo user={props.author} />
<div className="comment-text">{props.text}</div>
<div className="comment-date">{formatDate(props.date)}</div>
</div>
);
}
최종 코드 구조:
function Avatar(props) {
return <img className="avatar" src={props.user.avatarUrl} alt={props.user.name} />;
}
function UserInfo(props) {
return (
<div className="user-info">
<Avatar user={props.user} />
<div className="user-info-name">{props.user.name}</div>
</div>
);
}
function Comment(props) {
return (
<div className="comment">
<UserInfo user={props.author} />
<div className="comment-text">{props.text}</div>
<div className="comment-date">{formatDate(props.date)}</div>
</div>
);
}