리액트 생명주기 메서드

감소찌·2023년 8월 15일
0
post-thumbnail

혼자 공부하면서 정리한 글입니다. 오류가 있다면 알려주시길 바랍니다 🙇🏻

생명주기 메서드 (lifecycle method)

마운팅(생성)

  • 컴포넌트가 생성될 때 일련의 생명주기 메서드들이 호출되기 시작
  • 개발자는 이들 중 전부나 일부 메서드에 연결할 수 있는 옵션이 있다.
  • 생성자와 getDerivedStateFromProps, render, componentDidMount

갱신

  • 컴포넌트가 갱신될 때 호출
  • getDerivedStateFromPreops(props 변경시), shouldComponentUpage, render, getSnapshotBeforeUpate, compoenetDidUpdate
  • 갱신은 둘 중 하나로 이루어진다.
    • setStateforceUpate 메서드가 컴포넌트 내에서 호출될 때
    • props가 컴포넌트로 전달되 때

언마운팅(파기)

  • 컴포넌트가 언마운팅될 때 최종 생명주기 메서드가 시작
  • componentWillUnmount

static getDerivedStateFromProps 메서드

getDerivedStateFromPropsstatic 클래스 메서드로 컴포넌트가 생성될 때와 컴포넌트가 새 props를 전달받을 때 모두 호출된다.
새로운 props와 가장 최근의 state를 인수로 전달받아서 하나의 객체를 반환한다.
객체의 데이터는 컴포넌트의 state로 갱신된다.
Derived는 파생이란 뜻

export default class App extends Component {
  state = {
    userLoggedIn: false
  }
  static getDerivedStateFromProps(nextProps, nextState) {
    if (nextProps.user.authenticated) {
      return {
        userLoggedIn : true
      }
    }
    return null
  }
  render() {
    return (
      <View>
      	{
       	 this.state.userLoggedIn && (
        	<AuthenticatedComponent />
       	 )
  		}
	  </View>
	);
  }
}

componentDidMount 생명주기 메서드

componentDidMount는 컴포넌트가 로딩되고서 바로 한 번만 호출된다.
Ajax 호출로 가져온 데이터를 처리하거나, 지정된 실행 후에 실행되는 setTimeout 처리를 하거나, 다른 자바스크립트 프레임 워크들과 통합하기에 적절한 위치이다.

class MainComponent extends Component {
  constuctor() {
    super()
    this.state = { loading: true, data: {} }
  }
  conponentDidMount() {
    #simulate ajax call // Ajax 호출을 한다면
    setTimeout(() => {
      this.setState({
        loading: false,
        data: {name: '리액트 네이티브', age: 30}
      })
    }, 2000)
  }
  render() {
    if(this.state.loading) {
      return <Text>Loading</Text>
    }
    const { name, age } = this.state.data
    return (
      <View>
      	<Text>이름: {name}</Text>
      	<Text>나이: {age}</Text>
	  </View>
	)
  }
}

shouldComponentUpate 생명주기 메서드

shouldComponentUpate 메서드는 Boolean을 반환하며 컴포넌트의 랜더링을 할 것인지 결정할 수 있다.
새로운 stateprops가 컴포넌트나 자식 컴포넌트의 랜더링이 필요하지 않다고 판단되면 false를 반환한다.
컴포넌트를 다시 랜더링하고 싶다면 true를 반환한다

class MainComponent extends Component {
  shouldComponentUpdate(nextProps, nextState) {
    if(nextProps.name !== this.props.name) {
      return true // 랜더링 함
    }
    return false // 랜더링 안함
  }
  render() {
    return <SomeComponent />
  }
}

componentWillUnmount 생명주기 메서드

componentWillUnmount 메서드는 앱에서 컴포넌트가 파기되기 전에 호출된다.
componentDidMount 메서드에서 설정된 필요한 정리를 하고 리스너를 삭제하고, 타이머를 제거하도록 지정할 수 있다.

class MainComponent extends Component {
  handleClick() {
    this._timeout = setTimeout(() => {
      this.openWidget();
    }, 2000);
  }
  componentWillUnmount() {
    clearTimeout(this._timeout);
  }
  render() {
    return <SomeComponent
    	handleClick={() => this.handleClick() }/>
  }
}

함수형 컴포넌트에 익숙해서 뭔가 이런 메서드들이 낯설다;;

profile
감자 소시지 찌개

0개의 댓글