커링을 사용하지 않아도 원하는 기능을 대부분 구현할 수 있지만 재사용성이나 가독성에 따른 생산성 향상을 위해 커링을 사용하면 좋은 효과를 기대할 수 있습니다. 커링을 직접 구현하지 않더라도 커링의 개념과 사용법에 대해 알아두면 다른 사람의 코드를 읽거나 로직을 이해하는데 큰 도움이 될 것이라 생각합니다.
위와 같이 각각의 컴포넌트는 [ 마운팅 -> 업데이트(반복) -> 언마운팅 ]의 라이프사이클을 갖습니다.
이전에는 직관적인 이름을 갖는 다양한 메소드(componentWillMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate)를 통해 이벤트 발생 시점마다 세세한 조작이 가능했으나 현재는 버그나 안전성의 이유로 점점 더 단순해지고 있습니다.
위 기능을 모두 대체하는 훅(Hook)이 너무 편해서 클래스형 컴포넌트를 반드시 사용해야 하는 상황이 아니라면 함수형 컴포넌트와 함께 useEffect를 사용하는 방법이 권장되고 있습니다.
라이프사이클 별로 메소드를 사용하는 방법은 다음과 같습니다.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class TestList extends React.Component{
constructor(props){
super(props);
this.state = {
counter:0
}
}
// 마운팅 직후 실행
// 마운팅 전 실행은 constructor() 사용
componentDidMount(){
console.log('component Mounted');
}
// 업데이트 후 이전 데이터를 파라미터로 가져옴
componentDidUpdate(prevProps){
if(prevProps !== this.props){
this.setState({counter:++this.state.counter})
}
}
// 언마운팅 직전 실행
componentWillUnmount(){
console.log('component Unmounted');
}
render(){
return(
<div>{this.state.counter}</div>
);
}
}
class TestList extends React.Component {
constructor(props) {
super(props);
this.state = {
counter:0
}
}
// 마운팅 직후 실행
// 마운팅 전 실행은 constructor() 사용
componentDidMount(){
console.log('component Mounted');
}
// 업데이트 후 이전 데이터를 파라미터로 가져옴
componentDidUpdate(prevProps) {
if(prevProps !== this.props) {
this.setState({counter:++this.state.counter})
}
}
// 언마운팅 직전 실행
componentWillUnmount(){
console.log('component Unmounted');
}
render() {
return (
<div>{this.state.counter}</div>
);
}
}
class TestList extends React.Component {
constructor(props) {
super(props);
this.state = {
counter:0
}
}
// 마운팅 직후 실행
// 마운팅 전 실행은 constructor() 사용
componentDidMount(){
console.log('component Mounted');
}
// 업데이트 후 이전 데이터를 파라미터로 가져옴
componentDidUpdate(prevProps) {
if(prevProps !== this.props) {
this.setState({counter:++this.state.counter})
}
}
// 언마운팅 직전 실행
componentWillUnmount(){
console.log('component Unmounted');
}
render() {
return (
<div>{this.state.counter}</div>
);
}
}
마운팅 이벤트는 실제 DOM에 컴포넌트를 추가하는 이벤트입니다.
마운팅 이벤트는 다른 프레임워크나 라이브러리 또는 데이터와 연결하는 작업에 적절합니다.
업데이트 이벤트는 컴포넌트의 업데이트와 관련이 있으며, props, state 등의 변경이 있을 때 렌더링 관련한 작업을 설정합니다.
언마운팅은 DOM에서 요소를 분리하거나 제거하는 이벤트입니다.
언마운팅 이벤트는 타이머 제거, 요소 제거, 이벤트 제거 등 설정한 요소의 정리, 제거에 사용합니다.
2. 함수형 컴포넌트와 useEffect(Hook)
리액트 16.8부터 추가된 훅(Hook)은 클래스를 사용하지 않아도 state 또는 리액트의 여러 기능을 편하게 사용하도록 해주는 기능입니다.