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;
๋ฐ˜์‘ํ˜•