๐ŸŒReact Hooks (2).useEffect

ํ˜œ์ง„ ์กฐยท2022๋…„ 3์›” 7์ผ
0

๋ฆฌ์•กํŠธ

๋ชฉ๋ก ๋ณด๊ธฐ
2/31
post-thumbnail
post-custom-banner
import { useEffect, useState } from "react";

const Info = () => {
  const [name, setName] = useState("์กฐํ˜œ์ง„");
  const [nickName, setNickName] = useState("RootCho");

  useEffect(() => {
    console.log("๋งˆ์šดํŠธ ๋  ๋•Œ๋งŒ ์‹คํ–‰");

    return () => {
      console.log("์–ธ๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰");
    }; //์ด ์ปดํผ๋„ŒํŠธ๊ฐ€ ํ™”๋ฉด์—์„œ ์‚ฌ๋ผ์งˆ ๋•Œ ์‹คํ–‰. ๋’ท์ •๋ฆฌ(cleanup)ํ•จ์ˆ˜
  }, []);

  useEffect(() => {
    console.log("๋ Œ๋”๋ง์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."); //์ฒซ ๋งˆ์šดํŠธ ๋ ๋•Œ, name์ด ์—…๋ฐ์ดํŠธ ๋  ๋•Œ๋งˆ๋‹ค ์‹คํ–‰. Why? deps ๋ฐฐ์—ด์˜ value๊ฐ’์ด name์ด๋‹ˆ๊นŒ
    return () => {
      console.log("clean-up"); //๊ธฐ์กด name์ด ์ž…๋ ฅ์ฐฝ์—์„œ ์‚ฌ๋ผ์งˆ ๋•Œ ์‹คํ–‰
      console.log(name); //๊ธฐ์กด name์ด ์ฝ˜์†”์— ์ฐํž˜
    };
  }, [name]);

  return (
    <>
      <div>
        <input
          value={name}
          placeholder="์ด๋ฆ„"
          onChange={(e) => setName(e.target.value)}
        />
        <input
          value={nickName}
          placeholder="๋‹‰๋„ค์ž„"
          onChange={(e) => setNickName(e.target.value)}
        />
      </div>
      <h1>์ด๋ฆ„: {name}</h1>
      <h1>๋‹‰๋„ค์ž„: {nickName}</h1>
    </>
  );
};

export default Info;

useEffect

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

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

์ฒซ๋ฒˆ์งธ ์ธ์ž์—๋Š” ์ฝœ๋ฐฑํ•จ์ˆ˜, ๋‘๋ฒˆ์งธ ์ธ์ž์—๋Š” ์˜์กด์„ฑ ๋ฐฐ์—ด[ ]์ด ๋‹ด๊ธด๋‹ค.

useEffect(()=>{
console.log("๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰")}) //๋ Œ๋”๋ง๋  ๋•Œ ๋งˆ๋‹ค ์‹คํ–‰

useEffect(()=>{
console.log("๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰")},[ ]) //๋งจ ์ฒ˜์Œ ๋งˆ์šดํŠธ ๋˜์—ˆ์„ ๋•Œ ์‹คํ–‰ (์ตœ์ดˆ ํ•œ ๋ฒˆ)

useEffect(()=>{
console.log("๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰")},[name])//๋งจ ์ฒ˜์Œ ๋งˆ์šดํŠธ ๋˜์—ˆ์„ ๋•Œ ์‹คํ–‰ & ํŠน์ • ๊ฐ’(name)์ด ๋ Œ๋”๋ง ๋  ๋•Œ๋งˆ๋‹ค ์‹คํ–‰

useEffect(()=>{
console.log("๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰")

return () => {
     console.log("์–ธ๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰"); //๋’ท์ •๋ฆฌ(cleanup)ํ•จ์ˆ˜. ์ด ๋ถ€๋ถ„์€ ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์–ธ๋งˆ์šดํŠธ ๋˜์—ˆ์„ ๋•Œ ์‹คํ–‰ 
   }},[])

โ“ ์ปดํฌ๋„ŒํŠธ ๋ผ์ดํ”„์‚ฌ์ดํด

๋งˆ์šดํŠธ : ํŽ˜์ด์ง€์— ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋‚˜ํƒ€๋‚จ.
์—…๋ฐ์ดํŠธ(<-๋ฆฌ๋ Œ๋”๋ง) : ์ปดํฌ๋„ŒํŠธ ์ •๋ณด๋ฅผ ์—…๋ฐ์ดํŠธ.
์–ธ๋งˆ์šดํŠธ : ํŽ˜์ด์ง€์—์„œ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์‚ฌ๋ผ์ง.

profile
๋‚˜๋ฅผ ๋ฏฟ๊ณ  ํ•œ ๊ฑธ์Œ ํ•œ ๊ฑธ์Œ ๋‚ด๋”›๊ธฐ! ๐Ÿ
post-custom-banner

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