data life

[React] 생명주기 (Life-Cycle) 본문

Front-end/React

[React] 생명주기 (Life-Cycle)

주술회전목마 2023. 3. 29. 06:49
컴포넌트가 처음으로 렌더링 될 때, DOM에 mount

컴포넌트가 DOM에서 빠졌을 때, unmount

 

❓생명주기를 왜 알아야하죠?

최근에는 함수 컴포넌트를 사용하고 있지만 리액트 초기엔 클래스 컴포넌트를 많이 이용하였다.

클래스 컴포넌트는 기본적으로 생명주기에 따라 메서드를 제어할 수 있게 되어있고

함수 컴포넌트는 따로 hook() 함수를 이용해 컴포넌트의 mount, unmount 되는 시점에 맞춰 제어가 가능하다. 클래스 컴포넌트를 이해하기 위해서는 생명주기를 알아야한다.

 

그렇다면, 먼저 함수 컴포넌트와 클래스 컴포넌트를 비교해보자.

export default function Clock(){
   const [date, setDate] = useState(new Date());
   
   return(
     <>
       <h1>Hello!</h1>
       <h2>{date.toLocaleTimeString()}</h2>
     </>
   )
}
export default class Clock extends React.Component {
  constructor(props){
    super(props);
    this.state = {date:new Date()};
  }
  
  render(){
    return (
      <>
        <h1>Hello!</h1>
        <h2>{this.state.date.toLocaleString()}</h2>
      </>
    )
  }
}

기존에는 함수 컴포넌트를 이용하여 다루다보니 아무래도 익숙하지 않을 것이다.

가장 상단에 존재하는 constructor는 생성자로써 초기화를 담당하는 영역이다.

해당 Clock 컴포넌트에서 쓰일 state 들에 대한 정의는 이 부분에서 해주면 된다.

바로 아래, render() 초기 렌더링될 부분이다.

 

constructor 아래 다음과 같이 추가해보도록 하자.

tick() {
  this.setState({
    date : new Date(),
  });
}

componentDidMount(){
  console.log("componentDidMount!");
  this.timerID = setInterval(()=>this.tick(), 1000);
}

componentDidMount() 부분은 ReactDom가 업데이트 직후에 실행이 되는 메서드이다. 콘솔 창에 "componentDidMount!"가 한번만 나타나는 것을 확인할 수 있다. 즉, 한번만 일어나는 셈!

1초 뒤에 tick 함수를 실행하도록 해주는 메서드로 이때, tick함수에 setState가 존재하므로 1초 뒤에 변경된 state로 다시 렌더링이 된다. (위의 그림 참조)

 

마찬가지로, componentDidMount() 아래 다음과 같이 코드를 추가해보자.

componentDidUpdate(){
   console.log("componentDidUpdate!");
   console.log(this.state.date);
}

componentWillUnmount(){
   console.log("componentWillUnmount!");
   clearInterval(this.timerID);
}

 

컴포넌트가 업데이트될 때마다 componentDidUpdate() 메서드가 실행되며,

컴포넌트가 제거될 경우, componentWillUnmount() 메서드가 실행될 것이다.

 

 

 

'Front-end > React' 카테고리의 다른 글

[React] List와 Key 개념  (0) 2023.03.29
[React] Hook 함수 중 useEffect()  (0) 2023.03.29
[React] State 끌어올리기  (0) 2023.03.29
[React] State의 비동기적 업데이트  (0) 2023.03.29
[React] State  (0) 2023.03.29