컴포넌트가 처음으로 렌더링 될 때를 의미한다.
React는 컴포넌트를 마운트 할때 순서대로 4가지 내장 메소드를 호출하게 된다.
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
render() 메소드는 항상 호출 되어야 하며, 다른 메소드들은 선택적으로 호출 될 수 있다.
state
와 다른 초기값을 생성한다.컴포넌트가 업데이트 될 때를 의미한다.
컴포넌트의 state나 props가 변경될 때 마다 업데이트 된다.
React는 컴포넌트가 업데이트 되면 순서대로 5가지 내장 메소드를 호출하게 된다.
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
state
가 저장되는 곳이다.true
이다.render()
도 호출 된다. 변경된 값들로 리렌더링 된다.getSnapshotBeforeUpdate
메소드가 존재하면, componentDidUpdate()
메소드 또한 포함해야 한다. 그렇지 않을시 에러가 발생한다.컴포넌트가 DOM에서 제거하거나 unmount 될때를 의미한다.
React는 unmount 될 때엔, 하나의 내장 메소드가 호출된다.
componentWillUnmount()
제어 방식 비교
함수형 컴포넌트 | 클래스형 컴포넌트 |
---|---|
비교적 최근에 나옴 | 리액트 초기에 나옴 |
Hook 함수로 컴포넌트의 mount, unmount 되는 시점을 제어할 수 있음 | 생명 주기에 따른 메서드에 따라 제어할 수 있음 |
export default class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
// Clock 출력값이 DOM에 삽입되면, React는 componentDidMount() 생명주기 메서드를 호출
componentDidMount() {
console.log('componentDidMount');
this.timerID = setInterval(() => this.tick(), 1000);
}
// setState() 호출 덕분에 React는 state가 변경된 것을 인지하고 화면에 표시될 내용을 알아내기 위해 render() 메서드를 다시 호출
tick() {
this.setState({
date: new Date();
});
}
componentDidUpdate() {
console.log('componentDidUpdate');
console.log(this.state.date);
}
// Clock 컴포넌트가 DOM으로부터 한 번이라도 삭제된 적이 있다면 React는 타이머를 멈추기 위해 componentWillUnmount() 생명주기 메서드를 호출
componentWillUnmount() {
console.log('componentWillUnmount');
clearInterval(this.timerID);
}
render() {
return (
<div>
<h1>Timer</h1>
// this.state.date가 변경되고 렌더링 출력값은 업데이트 된 시각을 포함
<h2>It is {this.state.date.toLocaleTimeString()}</h2>
</div>
);
}
}
useEffect() Hook으로 제어.
useEffect(() => {}, []);
useEffect(() => {});
useEffect(() => {}, [state, props.a]);
useEffect(() => { return () => { cleanup }}, [state, props.a]);
export default function Clock() {
const [date, setDate] = useState(new Date());
const tick = () => {
setDate(new Date());
};
useEffect(() => {
// componentDidMount()와 같음.
console.log('componentDidMount');
const timerId = setInterval(tick, 1000);
// componentWillUnmount와 같음.
return () => {
clearInterval(timerId);
};
}, []);
useEffect(() => {
// componentDidUpdate()와 같음.
console.log('componentDidUpdate');
console.log(date);
}, [date]);
return (
<div>
<h1>Hello, wolrd!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
Multiple Effect 사용.