Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[React] ๋น„๋™๊ธฐ useState ๋™๊ธฐ๋กœ ์ฒ˜๋ฆฌํ•˜๊ธฐ ๋ณธ๋ฌธ

๐Ÿง‘‍๐Ÿ’ป Web/React

[React] ๋น„๋™๊ธฐ useState ๋™๊ธฐ๋กœ ์ฒ˜๋ฆฌํ•˜๊ธฐ

Lennon 2022. 6. 30. 22:36
728x90
๋ฐ˜์‘ํ˜•

๋‹ค๋“ค ๋ฆฌ์•กํŠธ ํ”„๋กœ์ ํŠธ์—์„œ useState๋ฅผ ์“ฐ๋ฉฐ ๋‹นํ™ฉํ–ˆ๋˜ ์ ์ด ์žˆ์„๊ฑฐ๋ผ ์ƒ๊ฐํ•œ๋‹ค.

๋ฆฌ์•กํŠธ์˜ useState๋ฅผ ์“ฐ๋‹ค๋ณด๋ฉด ์šฐ๋ฆฌ๊ฐ€ ์›ํ•˜๋Š” ๋Œ€๋กœ ๋™์ž‘ํ•˜์ง€ ์•Š๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์•„๋ž˜ ์ฝ”๋“œ๋Š” ์ฒดํฌ๋ฐ•์Šค๊ฐ€ ํ•˜๋‚˜ ์กด์žฌํ•˜๊ณ  ์ฒดํฌํ• ๋•Œ๋งˆ๋‹ค ์ƒํƒœ toggle ๊ฐ’์ด true or false๋ฅผ ๊ฐ€์ง€๋Š” ๋กœ์ง์ด๋‹ค. 

์ฒดํฌ๋ฐ•์Šค๋ฅผ ์ฒดํฌํ•˜๋Š” ๊ฑธ๋กœ ์ƒํƒœ๊ฐ’์„ ๋ฐ”๊พธ๋Š” ์˜ˆ์‹œ๋ฅผ ๋ณด๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์˜ˆ์ƒํ•ด๋ณด์ž

import React, { useState } from "react";

function App() {
  const [toggle, setToggle] = useState(false);

  const onChange = () => {
    setToggle((toggle) => !toggle);
    
    if(toggle) {
    	console.log('toggle์€ True');  // ๋ฌด์—‡์ด
    } else {
    	console.log('toggle์€ False'); // ๋‚˜์˜ฌ๊นŒ์š”
    }
  };

  return (
    <>
      <input type="checkbox" onChange={onChange} />
    </>
  );
}

์šฐ๋ฆฌ๋Š” ๋‹น์—ฐํ•˜๊ฒŒ๋„ ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ setToggle๋กœ ์ธํ•ด toggle ์ƒํƒœ๊ฐ’์ด true๋กœ ๋ณ€๊ฒฝ๋๊ณ , ๋ฐ‘์— if๋ฌธ์—์„œ toggle์€ True๊ฐ€ ์ถœ๋ ฅ๋ ๊ฑฐ๋ผ ์ƒ๊ฐํ•œ๋‹ค.

 

๊ทธ๋Ÿฌ๋‚˜ ํ—ˆ๋ฌดํ•˜๊ฒŒ๋„ ๋ฆฌ์•กํŠธ๋Š” ์šฐ๋ฆฌ ์˜ˆ์ƒ๊ณผ ๋‹ค๋ฅด๊ฒŒ toggle์€ false๊ฐ€ ์ถœ๋ ฅ๋˜๋Š” ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.(๋น„๋™๊ธฐ....๐Ÿ˜‡)

๊ทธ๋Ÿฌ๋‚˜ ๋ฆฌ์•กํŠธ๋Š” ์šฐ๋ฆฌ์—๊ฒŒ useEffect๋ผ๋Š” ๊ฐ•๋ ฅํ•œ ๋„๊ตฌ๋ฅผ ์ง€์›ํ•ด์ค€๋‹ค!!

 

useEffect ์‚ฌ์šฉ

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

function App() {
  const [toggle, setToggle] = useState(false);

  useEffect(() => {
  	if(toggle) {
    	console.log('toggle์€ True');
    } else {
    	console.log('toggle์€ False');
    }
  }, [toggle])
  
  const onChange = () => {
    setToggle((toggle) => !toggle);
  };

  return (
    <>
      <input type="checkbox" onChange={onChange} />
    </>
  );
}

useEffect๋ฅผ ์„ ์–ธํ•ด toggle์ด ๋ฐ”๋€”๋•Œ๋งˆ๋‹ค ํ•ด๋‹น ๋กœ์ง์ด ๋Œ์•„๊ฐ€๋„๋ก ๊ตฌ์„ฑํ•˜๋ฉด ๋ˆ„๊ฐ€๋ด๋„ ๋™๊ธฐ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฑธ ์•Œ ์ˆ˜ ์žˆ๋‹ค.
setState๋ฅผ ๋™๊ธฐ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ฐพ๊ธฐ๋ณด๋‹ค(์ฝ”๋“œ๊ฐ€ ์•„์ฃผ ๋”๋Ÿฌ์›Œ์งˆ ๊ฒƒ์ด๋‹ค), hook์—์„œ ์ œ๊ณตํ•˜๋Š” ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ๋“ค์„ ์‚ฌ์šฉํ•ด
๋™๊ธฐ์ ์ด๊ธธ ์›ํ•˜๋Š” ๋กœ์ง์„ ๊ตฌ์„ฑํ•ด๋ณด์ž!

 

์–ด๋–ค ์˜ค๋ฅ˜๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ ๋ถ€๋ถ„์—์„œ ํ•ด๊ฒฐ์ฑ…์„ ๊ณ ๋ฏผํ•  ๊ฒŒ ์•„๋‹ˆ๋ผ ๋„“๊ฒŒ ๊ณ ๋ฏผํ•˜๋Š” ์ž์„ธ๋ฅผ ๊ฐ€์ ธ์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค.

 

useEffect๋Š” ์•„์ฃผ ๊ฐ•๋ ฅํ•œ ๋„๊ตฌ์ด๋ฏ€๋กœ ๊ณต์‹ ๋ฌธ์„œ๋ฅผ ํ†ตํ•ด ์™„๋ฒฝํ•˜๊ฒŒ ์ตํžˆ๋Š” ๊ฑธ ์ถ”์ฒœํ•œ๋‹ค.

https://ko.reactjs.org/docs/hooks-effect.html

 

Using the Effect Hook – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

 

 

728x90
๋ฐ˜์‘ํ˜•
Comments