<aside> ๐Ÿ”ฅ useEffect?

์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง ๋ ๋•Œ๋งˆ๋‹ค ํŠน์ • ์ž‘์—…์„ ์ˆ˜ํ–‰ํ• ์ˆ˜ ์žˆ๋„๋ก ์„ค์ •ํ•ด์ฃผ๋Š” Hook.

ํด๋ž˜์Šคํ˜• ์ปดํฌ๋„ŒํŠธ์˜ componentDidMount + componentDidUpdate๋ฅผ ํ•ฉ์นœ ํ˜•ํƒœ

๊ธฐ๋ณธ ์ž‘์„ฑ ๋ฐฉ๋ฒ•

useEffect(() => {},[])

</aside>

<aside> ๐Ÿ”ฅ ์‚ฌ์šฉํ•ด๋ณด๊ธฐ

๋ Œ๋”๋ง ์‹œ์— useEffect๊ฐ€ ์ž‘๋™๋œ๋‹ค.

import React, { useEffect, useState } from "react";

const Info = () => {
  const [name, setName] = useState("");
  const [nickname, setNickname] = useState("");

  useEffect(() => {
    console.log("๋ Œ๋”๋ง์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!");
    console.log({
      name,
      nickname,
    });
  });

  const onChangeName = (e) => {
    setName(e.target.value);
  };

  const onChangeNickname = (e) => {
    setNickname(e.target.value);
  };

  return (
    <div>
      <div>
        <input value={name} onChange={onChangeName} />
        <input value={nickname} onChange={onChangeNickname} />
      </div>
      <div>
        <div>
          <b>์ด๋ฆ„:</b> {name}
        </div>
        <div>
          <b>๋‹‰๋„ค์ž„:</b> {nickname}
        </div>
      </div>
    </div>
  );
};

export default Info;

Untitled

</aside>

<aside> ๐Ÿ”ฅ ๋งˆ์šดํŠธ ๋ ๋•Œ๋งŒ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ

๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋นˆ ๋ฐฐ์—ด์„ ๋„ฃ์–ด์ฃผ๋ฉด ์—…๋ฐ์ดํŠธ ๋  ๋–„ ์‹คํ–‰๋˜์ง€ ์•Š๋Š”๋‹ค.

useEffect(() => {
    console.log("๋ Œ๋”๋ง์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!");
    console.log({
      name,
      nickname,
    });
  }, []);

</aside>

<aside> ๐Ÿ”ฅ ํŠน์ • ๊ฐ’์ด ์—…๋ฐ์ดํŠธ ๋ ๋•Œ๋งŒ ์‹คํ–‰ํ•˜๊ณ  ์‹ถ์„ ๋•Œ.

๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ์˜ ๋ฐฐ์—ด์— ๊ฒ€์‚ฌํ•˜๊ณ  ์‹ถ์€ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

๋ฐฐ์—ด ์•ˆ์—๋Š” useState๋ฅผ ํ†ตํ•ด ๊ด€๋ฆฌํ•˜๊ณ  ์žˆ๋Š” state๋ฅผ ๋„ฃ์–ด์ฃผ์–ด๋„ ๋˜๊ณ , props๋กœ ์ „๋‹ฌ๋ฐ›์€ ๊ฐ’๋„ ๊ฐ€๋Šฅ.

const [name, setName] = useState("");

useEffect(() => {
    console.log("๋ Œ๋”๋ง์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!");
    console.log({
      name,
      nickname,
    });
  }, [name]);

</aside>

<aside> ๐Ÿ”ฅ ๋’ท์ •๋ฆฌํ•˜๊ธฐ

useEffect๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ๋ Œ๋”๋ง ๋˜๊ณ  ๋‚œ ์งํ›„๋งˆ๋‹ค ์‹คํ–‰๋œ๋‹ค.

๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ฐฐ์—ด์— ์–ด๋–ค ๊ฐ’์„ ๋„ฃ๋Š”์ง€์— ๋”ฐ๋ผ ์‹คํ–‰๋˜๋Š” ์กฐ๊ฑด์ด ๋‹ฌ๋ผ์ง„๋‹ค.

์ปดํฌ๋„ŒํŠธ๊ฐ€ ์–ธ๋งˆ์šดํŠธ๋˜๊ธฐ ์ „์ด๋‚˜ ์—…๋ฐ์ดํŠธ๋˜๊ธฐ ์ง์ „์— ์–ด๋– ํ•œ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด

useEffect์—์„œ ๋’ท์ •๋ฆฌ ํ•จ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

</aside>