Don’t worry about failures

React DOCS Reading study(3) 본문

React

React DOCS Reading study(3)

허흥 2021. 6. 19. 14:31
728x90

State and Lifecycle

 

Lifecycle

리액트는 클래스형 컴포넌트와 함수형 컴포넌트가 존재한다. 

각각의 라이프 사이클에 살펴보자.

 

우선, 클래스형 컴포넌트를 보면, 

componentWillMount() {}

componentDidMount() {}

componentWillReceiveProps(nextProps) {}

shouldComponentUpdate(nextProps, nextStatus) {
   return true / false;
}

componentWillUpdate(nextProps, nextState) {}

componentDidUpdate(prevProps, prevState) {}

componentWillUnmount() {}

 

여기서 리액트 17부터는 componentWillMount, componentWillUpdate, componentWillReceiveProps 라이프 사이클이 deprecated!!

 

출처 : https://www.zerocho.com/category/React/post/579b5ec26958781500ed9955

Mount

컴포넌트 첫 실행 -> context, defaultProps, state 저장

-> componentWillMount() -> render를 통해 DOM에 부착 -> componentDidMount()

 

주의점

1. componentWillMount 시 props, state 변경 X

-> 아직 DOM에 render하지 않았기 때문에 DOM에 접근 불가.

-> componentDidMount 시점에서 props, state 변경

 

Props Update

props 변경 -> componentWillReceiveProps() -> shouldComponentUpdate() -> componentWillUpdate()

-> 업데이트 완료( render 완료 ) -> componentDidUpdate()

 

주의점

1. shouldComponentUpdate는 아직 render이전 이기 때문에 return false를 하면  render가 일어나지 않는다.

-> 이를 이요하여 성능 최적화 

2. componentWillUpdate에서는 state 변경 X

-> props가 아직 업데이트 하지 않았으므로 state를 바꾸면 또 shouldComponentUpdate가 발생.

 

State Update

setState를 통한 state 업데이트.

props 업데이트와 동일하지만, componentWIllReceiveProps 메소드는 호출 X

 

Unmount

컴포넌트 제거

 

그 다음 함수형 컴포넌트의 라이프 사이클에 대해 봐보자,

함수형 컴포넌트의 라이프 사이클은 클래스형과는 다른 라이프 사이클을 다루고 있다.

 

클래스형은 위에서 볼 수 있듯이 다양한 라이프 사이클 함수를 통해 관리를 한다. 반면에, 함수형의 경우 이를 대체하는 훅인 useEffect를 통해 관리를 한다.

 

useEffect의 경우 데이터, 즉 어떤 변수의 상태가 변할 때 마다 실행이 된다.

 

const [show, isShow] = useState(true);
useEffect( () => {
	console.log(show)
}, [show]);

 

위의 예제와 같이 show라는 변수가 변경될 때마다 useEffect는 호출이 된다.

클래스형과 비교해보면, componentDidMount와 componentDidUpdate가 합쳐진 함수와 같다.

 

componentWillUnmount의 역할도 할 수가 있다.

const [show, isShow] = useState(true);
useEffect( () => {
	console.log(show)
    return () => {
    	console.log('unmount')
    }
}, [show]);

 

이와 같이 useEffect 훅을 통해 다양한 접근을 할 수 있다. 첫 마운트 될 때 한번만 호출하고 싶을 때는 dependency를 빈배열로 넣고, 리렌더링 될 때마다 실행하고 싶을 때는 아애 없이 실행하면 된다. 

 

여기서 componentDidUpdate의 역할만, 즉 특정 변수가 변할 때만 실행되고 싶을 때는 useRef라는 훅을 사용한다.

( useEffect는 componentDidMount + componentDidupdate 역할 동시 수행 )

 

(훅에 대해서는 따로 Hook 딥하게 알보기 라는 컨셉을 잡고 새로운 글로 남기기로 한다.)

728x90

'React' 카테고리의 다른 글

React DOCS Reading study(5)  (1) 2021.06.23
React DOCS Reading study(4)  (0) 2021.06.22
React DOCS Reading study(2)  (0) 2021.06.18
React DOCS Reading study(1 - JSX)  (1) 2021.06.16
불변성  (0) 2021.05.08