[React] useEffect와 hook 생명주기(life-cycle)
1. class에서의 생명 주기

ref : projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
* component가 mount 시작 되면
1. constructor가 가장 먼저 실행
2. getDerivedStateFromProps에서 props와 state를 비교
3. render component
4. update DOM
5. componentDidMount가 실행
* component가 update 될 때 (new props or setState)
1. getDerivedStateFromProps에서 props와 state 비교
2. shouldComponentUpdate 실행 - new props, state를 확인하고 rerender 할 것인지 결정
3. rerender
4. update DOM
5. componentDidUpdate 실행
* component가 unmount 될 때
1. componentWillUnmount 실행
* 요약
최초 : constructor -> getDerivedStateFromProps -> componentDidMount
업데이트 : getDerivedStateFromProps -> componentDidUpdate
언마운트 : componentWillUnmount
1. Hook에서는 useEffet()가 위 생명주기 함수들을 대체합니다.
* useEffect의 기본 형태
useEffect(()=>{
console.log("");
})
- useEffect는 기본적으로 componentDidMount, componentDidUpdate, componentWillUnmount, getDerivedStateFromProps의 역할을 모두 합니다.
- 때문에 위 코드는 1) 컴포넌트가 마운트 된 후, 2) 컴포넌트가 업데이트되고 난 후 3) 컴포넌트가 언마운트 되기 전 모두 실행됩니다.
- useEffect는 아래와 같이 2가지의 인수를 받습니다. 하나는 useEffect가 실행할 함수이며, 두 번째는 이 함수를 실행시킬 조건입니다.
useEffect(<function>, <array>);
- useEffect는 함수를 반환할 수 있습니다. 이를 clean-up 이라고 표현합니다.
useEffect(()=>{
console.log("");
return(() => func());
})
- 이 clean-up함수는 useEffect가 실행될 때마다 실행됩니다.
* ComponentDidUpdate or getDerivedStateFromProps
- 위에서 useEffect는 1) 컴포넌트가 마운트 된 후, 2) 컴포넌트가 업데이트되고 난 후 3) 컴포넌트가 언마운트 되기 전 모두 실행된다고 했습니다.
- 이 때, 조건에 특정 state 혹은 props를 전달하면 이 state 혹은 props가 변할 때만 useEffect가 실행됩니다.
- 이는 class에서 componentDidUpdate, getDerivedStateFromProps와 같은 역할입니다.
cosnt { exampleProp } = props;
const [count, setCount] = useState(0);
useEffect(() => {
console.log("count or exampleProp changed");
},[count, exampleProp]);
* ComponentDidMount
- 위에서 조건으로 state를 전달하면 그 state가 변화할 때만 useEffect가 실행된다고 했습니다.
- 따라서, 이 배열을 빈 배열로 전달하면 useEffect는 컴포넌트 마운트시에만 실행됩니다.
- 이는 class에서 componentDidMount와 같은 역할입니다.
useEffect(()=>{
console.log("componentDidMount");
},[])
* ComponentWillUnmount
- ComponentWillUnmonut의 역할은 clean-up 함수를 통해 구현할 수 있습니다.
- 컴포넌트가 Unmount될 때 정리하거나 unscribe 해야할 것이 있다면 useEffect의 return 값으로 전달합니다.
useEffect(()=>{
console.log("");
return(() => exampleAPI.unsubscribe());
})