State Prev ๐Ÿ’ป

HSKwonยท2022๋…„ 5์›” 27์ผ
0

State Prev?๐Ÿค”

State Prev๋Š” ๋ฐ”๋กœ "์ง์ „" ๊ฐ’์„ ์˜๋ฏธํ•œ๋‹ค.

State Prev๊ฐ€ ํ•„์š”ํ•œ ์ด์œ ?

import { useState } from "react";

export default function CounterStatePage() {
  const [count, setCount] = useState(0);

  function counter() {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
  }

  return (
    <div>
      <div>{count}</div>
      <button onClick={counter}>์นด์šดํŠธ ์˜ฌ๋ฆฌ๊ธฐ!!!</button>
    </div>
  );

๐Ÿค”setCount(count+1)์„ ๋„ค๋ฒˆ ์ž…๋ ฅํ•œ๋’ค ๋ฒ„ํŠผ์„ ํด๋ฆญํ•ด๋„ ๊ฒฐ๊ณผ์ ์œผ๋กœ 1์”ฉ๋งŒ ์ฆ๊ฐ€ํ•˜๊ฒŒ๋œ๋‹ค!

โญ๏ธ์ด Counter ํ•จ์ˆ˜์•ˆ์—์„œ setState๋ฅผ ๋‹ค์„ฏ๋ฒˆ ์ฃผ์—ˆ์ง€๋งŒ, ๊ฒฐ๊ณผ๋Š” ํ•œ๋ฒˆ๋งŒ ๋”ํ•ด์ง„ 1์ด ๋‚˜์˜ค๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.setState์˜ ๊ฐ’์€ ๊ณ„์† ์ดˆ๊ธฐ๊ฐ’์ธ 0์ด ๋“ค์–ด๊ฐ€๊ธฐ ๋•Œ๋ฌธ์—,
๋‹ค์„ฏ๋ฒˆ ๋ชจ๋‘ 0+1 ์ด ๋œ๋‹ค. ๋ˆ„์ ๊ฐ’์„ ๊ตฌํ•˜๊ณ  ์‹ถ์„๋•Œ๋Š” prev๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.

Prev State๋ฅผ ์‚ฌ์šฉํ•œ ์˜ˆ์‹œโœ๏ธ

import { useState } from "react";

export default function CounterStatePage() {
  const [count, setCount] = useState(0);

  function counter() {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
    // setCount((prev) => prev + 1);
    // setCount((prev) => prev + 1);
    // setCount((prev) => prev + 1);
    // setCount((prev) => prev + 1);
  }

  return (
    <div>
      <div>{count}</div>
      <button onClick={counter}>์นด์šดํŠธ ์˜ฌ๋ฆฌ๊ธฐ!!!</button>
    </div>
  );
}


๋ˆ„์ ๊ฐ’์ด ์ž˜ ์˜ฌ๋ผ๊ฐ€๋Š” ๋ชจ์Šต

profile
๊ณต๋ถ€ํ•œ ๋‚ด์šฉ์ด๋‚˜ ๊ด€์‹ฌ ์žˆ๋Š” ์ •๋ณด๋ฅผ ๊ธ€๋กœ ์ •๋ฆฌํ•˜๋ฉฐ ์ต์ˆ™ํ•˜๊ฒŒ ๋งŒ๋“ค๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

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