Frontend/React
React | ๋ ๋๋ง ์ฃผ๊ธฐ - ์ ๊ฑฐ ๋จ๊ณ (Unmounting)
์ด์ ํฌ
2023. 12. 4. 18:00
- componentWillUnmount()
- ์๋ช ์ฃผ๊ธฐ ๋ฉ์๋ ์ค ํ๋
- ์ปดํฌ๋ํธ๊ฐ DOM์์ ์ธ๋ง์ดํธ(์ ๊ฑฐ) ๋๊ธฐ ์ ์ ํธ์ถ๋๋ค.
- ๋ฆฌ์์ค ํด์ , ํ์ด๋จธ ์ ๊ฑฐ, ์ด๋ฒคํธ ๋ฆฌ์ค๋ ํด์ ๋ฑ ์ปดํฌ๋ํธ ์ ๋ฆฌ ์์ ์ ์ํ ํ ์ ์๋ค.
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
timerId: null,
};
}
componentDidMount() {
// ์ปดํฌ๋ํธ๊ฐ ๋ง์ดํธ๋ ํ์ ํ์ด๋จธ๋ฅผ ์ค์
const timerId = setInterval(() => {
console.log('Timer is ticking...');
}, 1000);
// ํ์ด๋จธ ID๋ฅผ ์ํ์ ์ ์ฅ
this.setState({ timerId });
}
componentWillUnmount() {
// ์ปดํฌ๋ํธ๊ฐ ์ธ๋ง์ดํธ๋๊ธฐ ์ ์ ํ์ด๋จธ๋ฅผ ์ ๊ฑฐ
const { timerId } = this.state;
clearInterval(timerId);
console.log('Timer is cleared.');
// ๋ค๋ฅธ ์ ๋ฆฌ ์์
์ํ ๊ฐ๋ฅ
}
render() {
return (
<div>
<p>My Component</p>
</div>
);
}
}
export default MyComponent;
๋ฐ์ํ