React

리액트 LifeCycle API

쭈녁 2024. 5. 14. 23:36

리액트에는 요소의 라이프사이클에 따라 사용할 수 있도록 LifeCycle API를 제공한다.

해당 API를 통해 부모 자식관계의 요소들 사이에서 state와 props를 관리를 수월하게 해 준다.

 

나는 Spring 백엔드를 근간에 두고 있어 SpringFramwork에 비유하면서 공부하여 보았다.

스프링에도 라이프사이클에 의해 관리되도록 하는 어노테이션들이 있다. 리액트도 매우 비슷한 기능을 하는 API들을 만들어 놓은 것으로 이해되었다.

 

SpringBoot에서 라이프사이클에 해당하는 기능들

Bean Life Cylce에 해당하는

더보기

@PostConstruct

@PreDestroy

 

Bean의 생명주기와는 관련 있진 않지만 엔티티의 생명주기에 대응하도록 만들어진

더보기

@PostPersist

@PostUpdate

@PreRemove

애러 핸들링을 위한

더보기

@RestControllerAdvice

등과 비교하며 공부하니 이해가 편했던 것 같다.

 

 

리액트 LifeCycle API

constructor(props) : 생성자 호출 시 함수 실행

constructor(props) {
    super(props);
    console.log("constructor");
  }
  
/* 콘솔 로그
constructor
*/

 

componentDidMount(): 컴포넌트가 마운트 되고 실행되는 함수

constructor(props) {
    super(props);
    console.log("constructor");
  }
  componentDidMount() {
    console.log("componentDidMount");
    console.log(this.myDiv.getBoundingClientRect());
  }
  
 /*콘솔 로그
 	constructor
 	componentDidMount
	> DOMRect {내용}
 */

 


getDerivedStateFromProps() : 요소가 변경되었을 때 실행되는 함수 -> 생성 시에도 호출됨

/*컴포넌트 JS 코드 일부*/
  static getDerivedStateFromProps(props, state) {
    if (state.value !== props.value) {
      return {
        value: props.value,
      };
    }
    return null;
  }
  
  /*
  
  */
/*클릭 함수*/
	handleClick = () => {
		this.setState({ counter: this.state.counter + 1 });
	};
  
  
/*컴포넌트의 값을 업데이트*/
	{this.state.counter < 10 && <Mycomponent value={this.state.counter} />}
	<button onClick={this.handleClick}>Click here</button>

 

shouldComponentUpdate() : 컴포넌트를 업데이트할 조건을 설정(막을 때 사용)

이전값과 같다면 업데이트하지 마라 등의 최적화가 가능하게 한다.

/* 받은값이 10이면 업데이트 하지 않음 */
  shouldComponentUpdate(nextProps, nextState) {
    if (this.state.value === 10) {
      return false;
    }
    return true;
  }

 

getSnapshopBeforeUpdate()

컴포넌트가 업데이트가 되어서 DOM에 반영되기 직전에 호출되는 함수 DOM의 상태를 return 시켜서 받아오는 등의 활용

예시) 업데이트되기 전의 scroll 위치 or 인덱스 등의 값을 주어 상태를 유지하는 등 활용 가능하다.

 

componentDidUpdate()

컴포넌트가 업데이트되고 수행될 함수를 정의

  componentDidUpdate(prevProps, prevState) {
    if (this.props.value !== prevProps.value) {
      console.log("value 가 변함", this.props.value);
    }
  }
  /*
  value 가 변함 6
  value 가 변함 7
  ...
  */

 

componentWillUnmount()

  componentWillUnmount() {
    console.log("good bye");
  }
  /* 함수 로직 등으로 컴포넌트가 사라지면
	good bye
  */

 

componentDidCatch()

컴포넌트가 사용되는 부모 계층에서 함수를 작성해야 함

  componentDidCatch(error, info) {
    console.log(error, info);
  }