React에 클래스형 컴포넌트를 지양하고 함수형 컴포넌트를 권장하는 이유가 궁금했습니다.
우선 클래스형 컴포넌트는 컴포넌트가 언제 렌더링되고 파괴되는지(Lfiecycle), 그리고 각종 정보(DOM node 주소, Component 의 Instance)등을 가지고있습니다.
클래스형 컴포넌트
함수형 컴포넌트가 등장하기 이전의 컴포넌트 형태입니다.
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.childRef = React.createRef(); // 자식 컴포넌트 참조
this.state = { showChild: true };
}
toggleChild = () => {
this.setState({ showChild: !this.state.showChild });
};
componentDidMount() {
console.log("Parent mounted");
}
componentDidUpdate() {
console.log("Parent updated");
}
componentWillUnmount() {
console.log("Parent unmounted");
}
render() {
return (
<div>
<button onClick={this.toggleChild}>Toggle Child</button>
{this.state.showChild && <ChildComponent ref={this.childRef} />}
</div>
);
}
}
class ChildComponent extends React.Component {
componentDidMount() {
console.log("Child mounted");
}
componentWillUnmount() {
console.log("Child unmounted");
}
render() {
return <div>Child Component</div>;
}
}
이러한 문제는 아래 문제들을 야기합니다.
- 관리할 컴포넌트 늘어나면 Component 코드의 복잡도 증가
- 자식 Component 에게 부모 Component가 직접 접근하므로 decouple 하기 어려워집니다
함수형 컴포넌트
위 컴포넌트를 함수형 컴포넌트로 구현하면 아래와 같습니다.
function ParentComponent() {
const [showChild, setShowChild] = useState(true);
return (
<div>
<button onClick={() => setShowChild(!showChild)}>Toggle Child</button>
{showChild && <ChildComponent />}
</div>
);
}
function ChildComponent() {
useEffect(() => {
console.log("Child mounted");
return () => {
console.log("Child unmounted");
};
}, []);
return <div>Child Component</div>;
}
- useEffect()를 활용해 componentDidMount, componentWillUnmount 대체 → 코드가 간결해짐
- 부모-자식 관계가 느슨한 결합(Decoupling) 상태로 유지되어 컴포넌트 재사용 가능
위 코드 처럼 가능하게 된 이유가 뭘까요?
우선 클래스형 컴포넌트는 각 컴포넌트가 상태를 가지고 있지만, 함수형 컴포넌트는 React Element를 통해 어떤 정보를 구현할지에 대한 정보와 그것을 구현하는 구현체(함수형 컴포넌트)로 이루어져 느슨한 결합 상태로 유지가 가능합니다.
[React] Element란?
12개의 목차중에 3개까지 왔네요. 이번 글에서는 React Element에 대해 알아보겠습니다.Element란 ? React Element는 React가 화면에 렌더링할 수 있는 단순한 객체입니다. 이는 JavaScript 객체로 HTML 태그 또
my0366.tistory.com
React Element는 앞에서 소개한 내용인데, 참고하시면 도움이됩니다.
그런데 앞에서 소개한 내용중에, React Element 속성중에 Type이 있습니다.
{
type: 'button',
props: {
className: 'button button-blue',
children: {
type: 'b',
props: {
children: 'OK!'
}
}
}
}<button class='button button-blue'>
<b>
OK!
</b>
</button>
여기서 Type은 string또는 React Component가 오게되는데요, string이 올 때에는 일반적인 html 태그(a, p, button)등의 값들이 오게되고, React Component가 오게되면 해당 컴포넌트의 클래스이름이 오게됩니다. 이 내용은 아래와 연관되게 되는데 같이 봅시다!
Components Encapsulate Element Trees
{
type: Button,
props: {
color: 'blue',
children: 'OK!'
}
}
{
type: 'button',
props: {
className: 'button button-blue',
children: {
type: 'b',
props: {
children: 'OK!'
}
}
}
}
React 가 type 값이 React Component 인 Element(React component element)를 만나면
- type 값을 보고, 해당 component 함수에게 element 를 return 받는다
- return 받은 element 의 type 값이 tag name 인 element(DOM element)를 만날때까지 1번으로 돌아감
React 는 모든 React Component elements 가 React DOM elements 를 return 할때까지 위 과정 반복합니다. 이렇게되면 모든 elements 가 가진 DOM elements 를 알게 되고, React 가 해당 DOM elements 들의 Lifecycle을 관리하게됩니다. 따라서 기존 UI를 간단하게 구현할 수 있게 됩니다.
결론적으로 React element 를 활용하여, 기존에 DOM Structure를 모두 활용하지 않고, 필요한 정보만 독립적으로 UI 를 관리할 수 있게 된다는 점을 알게되었어요
이렇게 디테일한 내용까지 알아보며 저희가 JSX코드를 간결하게 작성하여 개발이 가능하다는 점을 깨달았는데 유익한 내용인 것 같습니다. 리액트에 대해 공부하면 트리구조로 점점 더 공부할 게 많아지는것같네요..^^
'Web > React' 카테고리의 다른 글
[React] Error Boundary란? (0) | 2024.12.05 |
---|---|
[React] React-Query 뽀개기 (0) | 2024.11.26 |
[React] 프로젝트 관리 시스템 만들기(feat . Supabase) (1) | 2024.11.21 |
[React] 렌더링 과정 알아보기 (6) | 2024.11.12 |
[React] Element란? (1) | 2024.09.05 |