부트캠프 수료 이후, 같은 포지션(FE)인 동기들 몇명과 함께 스터디를 진행 중이다. 오늘이 마침 온라인 회의를 하는 날이었는데 라이프사이클이 꽤나 중요한 주제이고 면접에서도 종종 나온다고 했다. 하지만 단번에 이해가 될 내용이 아니었다?
sks..나..난 천재가 아니라느뇽..! 난 한번에 이해를 할 수 없었다^^...
그래서 따로 정리를 해보겠다(당당)
라이프사이클...
다 외워버려ㅡㅡ 이해해버려ㅡㅡ 👊🏻
contructor
: 첫 번째로 실행되는 라이프사이클 함수.constructor()
내부에서 setState()
를 호출하면 안 됩니다.render
: UI 그려주는 함수componentDidMount
: UI가 세팅이 완료되면 우리에게 알려줌render
: state가 업데이트 되거나, props가 업데이트 되거나 또는 업데이트가 강요되는 상황일 때! render가 발생한다.componentDidUpdate
: state가 업데이트 된 후에 해야하는 작업들(ex.counter 값 바뀌는거) componentWillUnmount
: 컴포넌트 마운트 해제됨. 컴포넌트가 사라짐: 매개변수를 두개 받음(콜백함수,배열)
useEffect(()=>{ console.log("useEffect1 Fire") },[]) : 배열에 아무것도 없으면 componentDidMount()처럼 작동 (처음에만 렌더됨)
useEffect(()⇒{ console.log(”useEffect2 fire”) },[counter2]) : 배열 안에 state가 있으면 componentDidMount()+ componentDidUpdate() counter2 값 바뀔때마다 ”useEffect2 fire”
const [value1,setValue1]=useState(0) const [value2,setValue2]=useState(0) useEffect(()=>{ console.log("hey") },[value1,value2]) const updateValue =()=>{ setValue1(1) // 1개의 state만 업데이트 됨 } // 콘솔 결과는 hey 한번만 프린트 됨 ========================================================= const [value1,setValue1]=useState(0) const [value2,setValue2]=useState(0) useEffect(()=>{ console.log("hey") },[value1,value2]) const updateValue =()=>{ setValue1(1) // 2개의 state가 동시에 업데이트 됨 setValue2(1) } // 콘솔 결과는 hey 한번만 프린트 됨