React/기록

[React] 리액트 라이프사이클

Eater 2022. 12. 24. 17:00

공부를 위해 여러 블로그를 보며 정리 한 글

 

출처: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

라이프 사이클이란 함수형 컴포넌트에서의 생명주기를 말하며, 컴포넌트가 페이지에서 렌더링 되기 전인 준비 과정부터 시작해 페이지에서 사라질 때 끝이 난다.

 

 

라이프사이클의 분류

라이프 사이클은 총 9개가 존재하며 크게는 아래와 같이 세 가지 유형으로 나눌 수 있다.

더보기

componentDidMount : 렌더가 처음 실행될 때 실행되며 리렌더링이 일어날 땐 실행되지 않는다.

componentDidUpdate : 리렌더링 후에 실행된다.

componentWillUnmount : 컴포넌트가 제거되기 직전에 실행된다.

 

라이프사이클의 실행

리액트의 실행 순서를 정리하면 클래스의 경우 이 순서로 실행이 된다. (자주 안쓰이는 것 제외)

더보기

constructor -> render -> ref -> componentDidMount -> (setState/Props 바뀔때 -> shouldComponentUpdate -> render -> componentDidUpdate) -> componentWillUnmount -> 제거

하지만 함수형(Hooks)의 경우 componentDidMount, componentDidUpdate, componentWillUnmount가 각각 해주던 역할을 useEffect하나로 처리할 수 있게 되었다. 

  useEffect(() => { // componentDidMount, componentDidUpdate 역할(1대1 대응은 아님)
    console.log('다시 실행');
    return () => { // componentWillUnmount 역할
      console.log('종료');
    }
    // 실행하고 싶은 state (바뀌는 부분 // 없으면 1회만 실행됨 // 여러개 가능)
  }, [state]);

 

라이프사이클의 메서드

1. constructor

constructor(생성자) 컴포넌트가 만들어지면서 가장 먼저 실행되는 메서드. 초기 state값을 정할 수 있다.

// Class
class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
}

// Hooks
const Example = () => {
    const [count,setCount] = useState(0);
}

2. getDerivedStateFromProps

시간이 흐름에 따라 변하는 props에 가 의존하는 아주 드문 사용례를 위하여 존재한다. props로 받아 온 값을 state에 동기화 시키는 용도로 사용하며, 컴포넌트가 마운트될 때와 업데이트 될 때 호출된다.

다른 생명주기 메서드와는 달리 앞에 static을 필요로 하고, 이 안에서는 this 롤 조회할 수 없다. 여기서 특정 객체를 반환하게 되면 해당 객체 안에 있는 내용들이 컴포넌트의 state로 설정이 된다. 반면 null을 반환하게 되면 아무 일도 발생하지 않는다.

// Class
class Example extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== prevState.value) {
      return { value: nextProps.value }
    }
    return null
  }
}

Hooks에서의 getDerivedStateFromProps

 

3. shouldComponentUpdate

props나 state를 변경했을 때, 리렌더링을 할지 말지 결정하는 메서드다. 반드시 true나 false를 반환해야하며 오직 성능 최적화만을 위한 메서드이다.

// Class
shouldComponentUpdate(nextProps, nextState, nextContext) {
  if (this.state.counter !== nextState.counter) {
  	return true;
   }
   return false;
 }
 
 // Hooks
const Example = React.memo(() => {
      ...
  },
  (prevProps, nextProps, nextContext) => {
    return nextProps.value === prevProps.value
  }
)

 

4. render

컴포넌트를 렌더링 할 때 필수적인 메서드이다.

// Class
class Example extends React.Component {
  render() {
    return <div>컴포넌트</div>
  }
}

// Hooks
const example = () => {
  return <div>컴포넌트</div>
}

 

5. getSnapshotBeforeUpdate

 

render에서 만들어진 결과가 브라우저에 실제로 반영되기 직전에 호출된다. 공식문서에서는 채팅 화면처럼 스크롤 위치를 따로 처리하는 작업이 필요한 UI 등을 생각해볼 수 있다고한다.

class Example extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current
      return list.scrollHeight - list.scrollTop
    }
    return null
  }
}

아직 Hooks에서는 이 기능을 대체할 수 없다.

 

6. componentDidMount

렌더가 처음 실행될 때 실행되며 리렌더링이 일어날 땐 실행되지 않는다.

 

// Class
class Example extends React.Component {
    componentDidMount() {
        ...
    }
}

// Hooks
const Example = () => {
    useEffect(() => {
        ...
    }, []);
}

 

7. componentDidUpdate

리렌더링 후에 실행된다. 업데이트가 끝난 직후이므로, DOM관련 처리를 해도 무방하다.

// Class
class Example extends React.Component {
    componentDidUpdate(prevProps, prevState) {
        ...
    }
}

// Hooks
const Example = () => {
    useEffect(() => {
        ...
    });
}

 

8. componentWillUnmount

컴포넌트가 제거되기 직전에 실행된다. componentDidMount에서 등록한 이벤트가 있다면 여기서 제거 작업을 해야한다.

// Class
class Example extends React.Component {
    coomponentWillUnmount() {
        ...
    }
}

// Hooks
const Example = () => {
    useEffect(() => {
        return () => {
            ...
        }
    }, []);
}

 

9. componentDidCatch

컴포넌트 렌더링 도중에 에러가 발생 했을 때 애플리케이션이 멈추지 않고 오류 UI를 보여줄 수 있게 해준다.

// Class
class Example extends React.Component {
  componentDidCatch(error, info) {
    console.log('에러가 발생했습니다.')
  }
}

곧 Hooks에도 추가 될 계획이라고 한다.

 

 

참고:

https://kyun2da.dev/react/%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%9D%BC%EC%9D%B4%ED%94%84%EC%82%AC%EC%9D%B4%ED%81%B4%EC%9D%98-%EC%9D%B4%ED%95%B4/

https://www.youtube.com/playlist?list=PLcqDmjxt30RtqbStQqk-eYMK8N-1SYIFn