React :: useState

s_omiยท2022๋…„ 8์›” 3์ผ
0

React (๋ฆฌ์•กํŠธ)

๋ชฉ๋ก ๋ณด๊ธฐ
6/6

๐Ÿ’ก State

state๋Š” ๋ง ๊ทธ๋Œ€๋กœ ์ƒํƒœ๋ฅผ ๋งํ•˜๋Š” ๋ฐ ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ state์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ๋•Œ Hook์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ณ€๊ฒฝํ•˜๊ณค ํ•œ๋‹ค.

state๊ฐ€ var, let๋กœ ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋“ค๊ณผ ๋‹ค๋ฅธ ์ ์ด ๋ญ˜๊นŒ?

๋ฆฌ์•กํŠธ์—์„œ state๋ฅผ ์“ฐ๋Š” ๊ฐ€์žฅ ํฐ ์ด์œ ๋Š”
๋ฆฌ์•กํŠธ๋Š” state๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ ๊ทธ state๊ฐ€ ํฌํ•จ๋œ HTML์„ ์ž๋™์œผ๋กœ ์žฌ๋ Œ๋”๋ง ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

var, let๋กœ ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋“ค๋„ ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ์ด๋Š” HTML์„ ์ƒˆ๋กœ๊ณ ์นจ ํ•ด์•ผ ๋ณ€๊ฒฝ์ด ๋œ๋‹ค.

ํ•˜์ง€๋งŒ ์ด์™€ ๋‹ฌ๋ฆฌ state๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค ๊ฐ€์ƒ์˜ DOM์„ ์ž๋™์œผ๋กœ ์žฌ๋ Œ๋”๋งํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋น ๋ฅด๊ณ , ๋ถ€๋“œ๋Ÿฝ๊ฒŒ ํ™”๋ฉด์ „ํ™˜์ด ๋œ๋‹ค.


๐Ÿ’ก useState

useState๋Š” ์•ž์„œ ์„ค๋ช…ํ•œ state๋ฅผ state์˜ ์ƒํƒœ ๋ณ€๊ฒฝ ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ƒํƒœ๋ฅผ ๋ณ€๊ฒฝํ•˜๊ณ  ์ด๋ฅผ ํ™”๋ฉด์— ๋ฐ˜์˜ํ•ด์ค€๋‹ค.


๐Ÿ“ import

useState๋Š” ๋ฆฌ์•กํŠธ๊ฐ€ ์ œ๊ณตํ•ด์ฃผ๋Š” ์ผ์ข…์˜ ๋‚ด์žฅํ•จ์ˆ˜๋กœ ์ƒ๋‹จ์— import๋ฅผ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

import { useState } from 'react';

๐Ÿ“ ์˜ˆ์‹œ

function App() {
  const _count = useState(0);  // 0์œผ๋กœ ์ดˆ๊ธฐํ™”
  console.log(_count);         // (2) [0, f]
  
  const count = _count[0];     // ์ƒํƒœ์˜ ๊ฐ’
  const setCount = _count[1];  // ์ƒํƒœ์˜ ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ๋•Œ ์“ฐ๋Š” ํ•จ์ˆ˜ = ์ƒํƒœ ๋ณ€๊ฒฝ ํ•จ์ˆ˜
  console.log(count);          // 0

  const [count, setCount] = useState(0); // ์œ„์˜ ์ฝ”๋“œ ์„ธ ์ค„ ์ถ•์•ฝ 

  const onIncrease = () => { setCount(count + 1); };
  const onDecrease = () => { setCount(count - 1); };

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={onIncrease}> +1 </button>
      <button onClick={onDecrease}> -1 </button>
    </div>
  );
}
profile
๊ณต๋ถ€ํ•œ ๊ฑฐ ์˜ฌ๋ ค์š” :)

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