[React] ๐Ÿคœ๐Ÿ”ฅ๐Ÿค›ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ vs ํ•จ์ˆ˜ ์ปดํฌ๋„ŒํŠธ

TATAยท2023๋…„ 2์›” 4์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
9/32
post-thumbnail

์•„๋ž˜ ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ์™€ ํ•จ์ˆ˜ ์ปดํฌ๋„ŒํŠธ๋Š” ๊ฐ™์€ ๋™์ž‘์„ ํ•œ๋‹ค.

๐Ÿ”ฅ ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ

ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ๋กœ, 5์ดˆ๋งˆ๋‹ค count๊ฐ€ 1์ด ์ฆ๊ฐ€ํ•˜๋„๋ก ๋งŒ๋“ค์—ˆ๋‹ค.

// React ์ปดํฌ๋„ŒํŠธ class๋ฅผ ์ •์˜ํ•˜๋ ค๋ฉด, React.Component๋ฅผ ์ƒ์† ๋ฐ›์•„์•ผํ•œ๋‹ค.
class Count extends React.Component {
  constructor(props) {
    super(props); // ๋ถ€๋ชจ์˜ props
    this.state = { count: 0 }; // state ์ดˆ๊ธฐ๊ฐ’ ์ง€์ •
  }

  increase() {
    this.setState({ // ์ดˆ๊ธฐ๊ฐ’ ๋ณ€๊ฒฝ
      count: this.state.count + 1,
    });
  }
  
  // ์ปดํฌ๋„ŒํŠธ์˜ ์ถœ๋ ฅ๋ฌผ์ด DOM์— ๋ Œ๋”๋ง ๋œ ํ›„์— ํ•œ๋ฒˆ๋งŒ ์‹คํ–‰
  componentDidMount() {
    console.log("mount");
    this.timeIncrease = setInterval(() => this.increase(), 5000);
  }
  
  // ์ปดํฌ๋„ŒํŠธ์˜ ์—…๋ฐ์ดํŠธ๋งˆ๋‹ค ํ˜ธ์ถœ. ์ตœ์ดˆ ๋ Œ๋”๋ง ๋•Œ๋Š” ํ˜ธ์ถœ๋˜์ง€ ์•Š์Œ
  componentDidUpdate() {
    console.log("update");
    console.log(this.state.count);
  }
  
  // ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ œ๊ฑฐ๋˜๊ธฐ ์ง์ „์— ํ•œ๋ฒˆ๋งŒ ์‹คํ–‰
  componentWillUnmount() {
    console.log("unmount");
    clearInterval(this.timeIncrease);
  }

  // React.Component์˜ ํ•˜์œ„ class์—์„œ๋Š”
  // ๋ฐ˜๋“œ์‹œ render๋ฉ”์„œ๋“œ๋ฅผ ์ •์˜ํ•ด์•ผ ํ•œ๋‹ค.
  render() {
    return (
      <>
        <h1>Hello world!</h1>
        <h2>Count: {this.state.count}</h2>
      </>
    );
  }
}

๐Ÿ”ฅ ํ•จ์ˆ˜ ์ปดํฌ๋„ŒํŠธ

ํ•จ์ˆ˜ ์ปดํฌ๋„ŒํŠธ๋กœ, 5์ดˆ๋งˆ๋‹ค count๊ฐ€ 1์ด ์ฆ๊ฐ€ํ•˜๋„๋ก ๋งŒ๋“ค์—ˆ๋‹ค.

const CountFunction = () => {
  const [count, setCount] = useState(0);

  const increase = () => {
    setCount((count) => count + 1);
  };

  useEffect(() => {
    console.log("mount");
    const timeIncrease = setInterval(increase, 5000);

    // ๊นจ๋—ํ•˜๊ฒŒ ์ •๋ฆฌํ•ด์•ผ ํ•˜๋Š” ์ฝ”๋“œ๋Š” return๋ฉ”์„œ๋“œ ์•ˆ์— ์ž‘์„ฑํ•˜๋ฉด ๋œ๋‹ค.
    return () => {
      console.log("unmount");
      clearInterval(timeIncrease);
    };
  }, []);

  // ์ด๋ ‡๊ฒŒ ๊ธฐ๋Šฅ์— ๋งž๊ฒŒ useEffect๋ฅผ ๋ถ„๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.
  useEffect(() => {
    console.log("update");
    console.log(count);
  }, [count]);

  return (
    <>
      <h1>Hello world!</h1>
      <h2>Count: {count}</h2>
    </>
  );
};

๐Ÿ‘‰ ์ง€๊ธˆ ๋ฐ”๋กœ (๊ณต์‹๋ฌธ์„œ)React.Component ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
๐Ÿ‘‰ lifecycle diagram ๋ผ์ดํ”„์‚ฌ์ดํด ๋‹ค์ด์–ด๊ทธ๋žจ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ

profile
๐Ÿพ

0๊ฐœ์˜ ๋Œ“๊ธ€