[React] React의 필수요건, LifeCycle API

CHAI53·2019년 11월 5일
4

개인이 특정 텍스트를 한번 읽을 때, 어느 정도의 이해도를 보이게 될까.
LifeCycle API에 대한 글은 지금 5번 정도 읽게 된 것 같다.
처음에 읽을 땐 까만건 글씨, 하얀건 바탕. 그냥 아, 그런가 보다.
두번째 읽을 땐 아 전번에 봤던 거다.
세번째 읽을 땐 아, 전번에 봐서 조금 익숙한 것도 같다.

세션에 들어가서 예리님 코드를 잠깐 훔쳐보고 실전에서는 저렇게 쓰이는구나를 보고나니 이제서야 아, 저걸 진짜 알아야 하는구나, 대충 어떻게 쓰는거구나 하는 감이 오기 시작했다.
다시 읽으니 또 새로 보인다.

나는 언제쯤 진짜 개발자가 될 수 있을까.
언제쯤 이 자학의 지옥에서 나갈 수 있을까.

복붙에 가까운 블로깅이지만 그래도 한번 쓰고 정리하며 보는 것과 그냥 읽는 건 다르니까,
코드 짜기에도 숨막히는 일분일초지만 그래도 한 줄 쓰고 간다.

LifeCycle API란,

LifeCycle API란 컴포넌트가 DOM 위에 생성되기 전 후나 데이터가 변경되어 상태를 업데이트하기 전 후로 실행되는 메소드들을 의미한다.

component안에서 method의 실행순서

  • 컴포넌트 생성시: constructor -> componentWillMount -> render -> componentDidMount 순으로 진행

  • 컴포넌트 제거시: componentWillUnmount 메소드만 실행

  • 컴포넌트의 props 변경시: componentWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate-> render -> componentDidUpdate 순으로 진행

  • 컴포넌트의 state 변경시: shouldComponentUpdate -> componentWillUpdate-> render -> componentDidUpdate 순으로 진행

각 메소드들의 역할

constructor

  	constructor(props){
    	super(props);
    	console.log("constructor");
	}

생성자 메소드로서 컴포넌트가 처음 만들어 질 때 실행된다.
여기서 기본 state를 정할 수 있다. 이때 state란 이 메소드 안에서만 유효한 값들을 의미한다.

componentWillMount

	componentWillMount(){
    	console.log("componentWillMount");
	}

컴포넌트가 DOM 위에 만들어지기 전에 실행된다.

render

	render(){
      ...
    }

컴포넌트 렌더링을 담당한다.

componentDidMount

	componentDidMount(){
    	console.log("componentDidMount");
	}

컴포넌트가 만들어지고 첫 렌더링을 다 마친 후 실행되는 메소드이다.
이 안에서 다른 JavaScript 프레임워크를 연동하거나, setTimeout, setInterval 및 Ajax 처리 등을 넣는다.

componentWillReceiveProps

	componentWillReceiveProps(nextProps){
    	console.log("componentWillReceiveProps: " + JSON.stringify(nextProps));
	}

컴포넌트가 props를 새로 받았을 때 실행된다.
props의 변경에 따라 state를 업데이트 해야 할 때 사용하면 유용하다.
이 안에서 this.setState() 를 하더라도 추가적으로 렌더링하지 않는다.

shouldComponentUpdate

	shouldComponentUpdate(nextProps, nextState){
    	console.log("shouldComponentUpdate: " + JSON.stringify(nextProps) + " 						"+JSON.stringify(nextState));
    	return nextProps.id !== this.props.id;
	}

props 혹은 state 가 변경 되었을 때, 리렌더링을 할지 말지 정하는 메소드이다.
위 예제에선 무조건 true를 반환하지만, 실제로 사용할 떄는 필요한 비교를 하고 값을 반환하여야 한다.

cf. JSON.stringify() 를 쓰면 여러 field 를 편하게 비교 할 수 있다.

componentWillUpdate

	componentWillUpdate(nextProps, nextState){
    	console.log("componentWillUpdate: " + JSON.stringify(nextProps) + " " + 					JSON.stringify(nextState));
	}

컴포넌트가 업데이트 되기 전에 실행된다.
이 메소드 안에서 this.setState() 를 사용할 경우 무한루프에 빠지므로 주의해야 한다.

componentDidUpdate

	componentDidUpdate(prevProps, prevState){
    	console.log("componentDidUpdate: " + JSON.stringify(prevProps) + " " + 						JSON.stringify(prevState));
	}

컴포넌트가 리렌더링을 마친 후 실행된다.

componentWillUnmount

	componentWillUnmount(){
    	console.log("componentWillUnmount");
	}

컴포넌트가 DOM 에서 사라진 후 실행되는 메소드이다.

profile
꾸준함의 힘

1개의 댓글

comment-user-thumbnail
2023년 6월 2일

좋은글 감사합니다 ㅜㅜ
저도 막 배워서 까만건 글씨, 하얀건 바탕으로 보이네요

답글 달기