[React] useState

-ยท2022๋…„ 11์›” 26์ผ
0
post-custom-banner

useState

useState๋Š” Hook์˜ ๊ธฐ์ˆ ์ด๋‹ค. ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ๋Š” ํด๋ž˜์Šคํ˜• ์ปดํฌ๋„ŒํŠธ์™€ ๊ฐ™์ด state๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์—, Hook์„ ์‚ฌ์šฉํ•ด์„œ state์™€ ๊ฐ™์€ ๊ธฐ๋Šฅ์„ ํ•  ์ˆ˜ ์žˆ๋„๋ก ๋งŒ๋“ค์–ด์ฃผ์—ˆ๋‹ค.

useState๋Š” ์„ค์ •ํ•  state ๊ฐ’๊ณผ ์ด ๊ฐ’์„ ์—…๋ฐ์ดํŠธํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์Œ์œผ๋กœ ์ œ๊ณตํ•œ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ํด๋ž˜์Šค ์ปดํฌ๋„ŒํŠธ์—์„œ์˜ this.setState์™€ ์œ ์‚ฌํ•˜์ง€๋งŒ ์ด์ „ state์™€ ์ƒˆ๋กœ์šด state๋ฅผ ํ•ฉ์น˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์ฐจ์ด์ ์ด ์žˆ๋‹ค.

๐Ÿ“Œ const [state, setState] = useState(์ดˆ๊ธฐ๊ฐ’);

  • state : ์ปดํฌ๋„ŒํŠธ์˜ ์ƒํƒœ
  • setState : state๋ฅผ ๋ณ€๊ฒฝํ•ด์ฃผ๋Š” ํ•จ์ˆ˜
  • state์˜ ์ƒ์„ฑ๊ณผ ๋™์‹œ์— ๊ฐ€์ ธ์•ผํ•  ์ดˆ๊ธฐ๊ฐ’์„ usestate ํ•จ์ˆ˜์— ์ธ์ž๋กœ ๋„ฃ์–ด์ฃผ๋ฉด
    state์™€ setState๋ผ๋Š” ๋‘๊ฐ€์ง€ ์š”์†Œ๋ฅผ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ returnํ•ด์ค€๋‹ค.
  • ํ˜„์žฌ ์ƒํƒœ๊ฐ’์„ state๋ผ๋Š” ๋ณ€์ˆ˜์— ๋“ค์–ด์žˆ๊ณ , state์˜ ๊ฐ’์„ ๋ณ€๊ฒฝ์‹œ์ผœ์ฃผ๊ธฐ์œ„ํ•ด setState ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ๋‹ค.
  • setState ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ state๋ฅผ ๋ณ€๊ฒฝํ•˜๋ฉด ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋Š” ํ™”๋ฉด์— ๋‹ค์‹œ ๋ Œ๋”๋ง(์—…๋ฐ์ดํŠธ)๋œ๋‹ค.

useState hook์„ ์ด์šฉํ•˜์—ฌ ์•„๋ž˜์™€ ๊ฐ™์ด ์˜ˆ์ œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ณด์•˜๋‹ค.


import React, { useState } from "react";

function App() {
  const [names, setNames] = useState(["ํ™๊ธธ๋™", "๊น€๋ฏผ์ˆ˜"]);
  const [input, setInput] = useState("");

  const handleInputChange = (e) => {
    setInput(e.target.value);
  };

  //์ƒˆ๋กœ ์—…๋ฐ์ดํŠธ ์‹œ์ผœ ์ค„ state๋Š” ์ด์ „์— ์ด๋ฏธ ์กด์žฌํ•˜๋˜ state์™€ ๋ฐ€์ ‘ํ•˜๊ฒŒ ์—ฐ๊ด€์ด ์žˆ๋‹ค.
  //์ด ๊ฒฝ์šฐ setNames ์ธ์ž ์•ˆ์— ๋ฐ”๋กœ ๊ฐ’์„ ์ฃผ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌํ•ด์ค€๋‹ค.
  
  const handleUpload = () => {
    setNames((prevState) => {
      return [input, ...prevState];
    }); 
    setInput(""); // upload ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅธํ›„ input์„ ๋นˆ์นธ์œผ๋กœ ํ•ด์ฃผ๋Š” ์ž‘์—…
  };

  // console.log(input); 

  return (
    <div>
      <input type="text" value={input} onChange={handleInputChange} />
      <button onClick={handleUpload}>Upload</button>
      {names.map((name, index) => {
        return <p key={index}>{name}</p>;
      })}
    </div>
  );
}

export default App;


array.map()
array.map() ์€ ๋ฐฐ์—ด ๋‚ด์˜ ๋ชจ๋“  ์š”์†Œ ๊ฐ๊ฐ์— ๋Œ€ํ•˜์—ฌ ์ฃผ์–ด์ง„ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ชจ์•„ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฉ”์„œ๋“œ์ด๋‹ค.
map์˜ index๋กœ key๋ฅผ ์žก๋„๋ก ์ž‘์„ฑํ•˜์˜€๊ณ  ์ž…๋ ฅ ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด ์‚ฌ๋žŒ ์ด๋ฆ„์ด ์š”์†Œ๋กœ ์ถ”๊ฐ€๋˜๋„๋ก ์„ค์ •ํ•˜์˜€๋‹ค.


input ์ฐฝ์— ์œค์ฝ”๋”ฉ๊ณผ ๊น€๊ฐœ๋ฐœ์„ ์ž…๋ ฅํ›„ upload ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด list-up ๋˜๋Š”๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. ๐Ÿ˜Š

์ถœ์ฒ˜ : [youtube] ๋ณ„์ฝ”๋”ฉ ์ฑ„๋„์„ ์ฐธ๊ณ ํ•˜์—ฌ ์ž‘์„ฑ๋œ ๊ธ€์ž…๋‹ˆ๋‹ค.

post-custom-banner

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