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>
);
โญ๏ธ์ด 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>
);
}
๋์ ๊ฐ์ด ์ ์ฌ๋ผ๊ฐ๋ ๋ชจ์ต