리엑트 라이프 사이클을 공부한 이유
- 프론트엔드 데브코스 면접 질문이였는데 대답을 하지 못함
- 나중에 면접 준비할 때 참고용
- 컴포넌트의 라이프 사이클을 숙지하고 있어야 컴포넌트 관련 작업을 처리함에 있어 각 구간에 의도에 맞도록 작업을 할 수 있을 것 같아서
- 특정 구간에 문제가 생겼을 때 그 구간에 대해 알고 있다면 대처가 빨라질 수 있으므로
리엑트란?

- View를 중심으로하는 component 기반의 js 라이브러리
facebook
에서 제공
- 싱글 페이지 어플리케이션 및 모바일 어플리케이션 개발에 토대
리엑트 라이프사이클

- 생성 될 때: mount
- 업데이트 될 때: update
- 제거 할 때: unmount
업데이트가 일어나는 상황
- props 수정
function Example (props) { return <h1>Hello, {props.name}</h1>; } const root = ReactDOM.createRoot(document.getElementById('root')); const element = <Example name="park" />; root.render(element);
- state 수정
const [increase, setIncrease] = useState(0); ... setIncrease((prev) => prev + 1);
- 부모 컴포넌트의 re-render
- this.forceUpdate로 강제로 렌더링을 트리거할 때
- state 또는 props의 변화에 의해 re-render가 되는데, state나 props가 아닌 data에 의해 rernder가 되기를 원할 때 사용
- React 공식 문서에서는 최대한 사용을 피하고, state나 props를 통해 re-render 되도록 권고
리엑트 라이프사이클 함수
constructor
- 초기 state 값을 설정
- class 형에서는
constructor
메소드 안에서 설정, Hooks에서는 useState hook 이용
class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } const Example = () => { const [count,setCount] = useState(0); }
- super(props) ⇒ React.component 객체가 생성 될 때 props를 초기화하기 위해 부모 컴포넌트에게
props
를 전달
- super를 사용해야 하는 이유 및 props를 전달해야 하는 이유
getDerivedStateFromProps
- props를 받아와서 state를 동기화 시킬 때 사용
- component가 mount및 update 될 때 호출
class Example extends React.Component { static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.value !== prevState.value) { return { value: nextProps.value } } return null } }
shouldComponentUpdate
- props나 state가 변경 되었을 때 re-render 여부를 결정하는 메소드(true or false 반환)
- 성능 최적화를 위해 사용
- 렌더링 방지를 위해 사용하면 버그를 발생시킬 수 있음
// Class class Example extends React.Component { shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value } } // Hooks const Example = React.memo(() => { ... }, (prevProps, nextProps) => { return nextProps.value === prevProps.value } )
render
- 컴포넌트를 렌더링할 때 필요함
가장 중요한 메소드
class Example extends React.Component { render() { return <div>컴포넌트</div> } } // Hooks const example = () => { return <div>컴포넌트</div> }
getSnapshotBeforeUpdate
- render로 인해 화면에 반영되기 직전에 호출되는 메소드
- 사용 빈도가 낮음
componentDidMount
- 컴포넌트를 처음 rendering 한 후 수행되는 함수
class Example extends React.Component { componentDidMount() { ... } } // Hooks const Example = () => { useEffect(() => { ... }, []); }
ComponentDidUpdate
- 컴포넌트가 re-render 되고 난 후 수행되는 함수
// Class class Example extends React.Component { componentDidUpdate(prevProps, prevState) { ... } } // Hooks const Example = () => { useEffect(() => { ... }); }
componentWillUnmount
- 컴포넌트를 DOM에서 제거할 때 실행
- componentDidMount로 등록한 컴포넌트가 있다면 해당 함수에서 제거해야 함
- hook은 useEffect의 cleanup 함수 사용
// Class class Example extends React.Component { coomponentWillUnmount() { ... } } // Hooks const Example = () => { useEffect(() => { return () => { ... } }, []); }
componentDidCatch
- rendering 중에 오류가 발생하였을 때 오류 UI를 보여줄 수 있는 메소드
- 관련 메소드 Hooks 추가 예정
// Class class Example extends React.Component { componentDidCatch(error, info) { console.log('에러가 발생했습니다.') } }
정리
Class | Hooks |
constructor | useState |
getDerivedStateFromProps | |
shouldComponentUpdate | React.memo |
render | render 없이 사용 |
getSnapshotBeforeUpdate | x |
componentDidMount | useEffect |
ComponentDidUpdate | useEffect |
componentWillUnmount | useEffect(clean 함수) |
componentDidCatch | 추가 예정 |