constructor(props)는 클래스형 컴포넌트에서컴포넌트를 초기화할 때 사용.
🖥️ javascript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
console.log('constructor 호출');
}
}
React에서 constructor는 반드시 필요한 메서드는 아니다.
많은 경우, state를 선언하거나 이벤트 핸들러를 바인딩하는 작업을 클래스 필드로 처리할 수 있기 때문에, constructor를 생략하는 경우가 늘고 있다. 따라서, constructor를 반드시 사용해야 하는 라이프사이클 메서드로 보지 않기도 한다.
이 메서드는 컴포넌트가 업데이트되기 전, 다시 렌더링할지 여부를 결정한다.
🖥️javascript
shouldComponentUpdate(nextProps, nextState) {
if (this.state.value !== nextState.value) {
console.log('업데이트 필요');
return true;
}
console.log('업데이트 불필요');
return false;
}
React에서는 성능 최적화를 위해 shouldComponentUpdate를 사용하지만, 최근에는 React.PureComponent나 React.memo() 같은 최적화 도구가 도입되어 이 메서드의 사용이 줄어들었다. 이런 이유로 최신 코드에서는 생략되는 경우가 많다.
클래스 필드 문법을 사용하여 state를 초기화하거나 핸들러를 바인딩.
🖥️ javascript
class MyComponent extends React.Component {
state = { counter: 0 };
}
PureComponent 또는 React.memo()를 사용하면,
깊은 비교 없이 props와 state의 얕은 비교만으로 최적화가 가능.
🖥️ javascript
const MyComponent = React.memo((props) => {
return <div>{props.value}</div>;
});
React 생태계가 발전하면서, constructor는 최신 문법으로 대체할 수 있고,
shouldComponentUpdate는 PureComponent나 React.memo()로 대체된다.
그러나 레거시 코드에서는 여전히 이 메서드들이 많이 사용되기 때문에, 기본 개념을 알고 있는 것이 중요!