
โจ ์ธ์ฌ์ดํธ
๋ฆฌ์กํธ ๊ฐ์๋ฅผ ์ฌ์๊ฐํ๋ฉฐ ์ ์ฒด ๊ฐ๋
๋ค์ ๋ํด ๋ณต๊ธฐํ๋ฉฐ ์ป์ ์ธ์ฌ์ดํธ.
๋ถ๋ชจ ์ปดํฌ๋ํธ์ setState๋ฅผ ์์ ์ปดํฌ๋ํธ์ props๋ก ๊ทธ๋๋ก ์ ๋ฌํ๋ ๋ฒ์ ๋ํด ๋ค์ ํ๋ฒ ์๊ฐํ๋ ๊ณ๊ธฐ๊ฐ ๋์๋ค.
โ
์์ง ๋ง์!
setState๋ฅผ ๊ทธ๋๋ก ์ ๋ฌํ๋๊ฑด ์ธ๋ถ์ ๋ฐ์ดํฐ ๋ณ๊ฒฝ์ ์ฃผ๋๊ถ์ ๋๊ฒจ์ฃผ๋ ๊ฒ๊ณผ ๊ฐ๋ค.
๊ทธ๋ฌ๋ฏ๋ก ์ฝ๋ฐฑํจ์๋ก ๊ฐ์ธ์ ๋๊ธฐ๊ณ ์์ ์ปดํฌ๋ํธ๊ฐ ๊ทธ๊ฒ์ ์ ์ ํ ์์ ์ ํธ์ถ๋ง ํ ์ ์๋๋ก ์ ์ด!๊ทธ๋ ๊ฒ ๋๋ฉด ํธ์ถํ๋ ์
์ฅ์์๋ ์ธ๋ถ ๋ก์ง์ ์๊ธฐ ์ด๋ ค์
์ปดํฌ๋ํธ ๋ด ๋ฐ์ดํฐ์ ์ฃผ๋๊ถ์ ๊ทธ๋๋ก ์ง์ผ๋ด๋ฉด์, ์ปดํฌ๋ํธ ๊ฐ์ ํ๋ ฅ
import { useState } from 'react';
import './App.css';
import Counter from './components/Counter';
export default function AppCounter() {
const [count, setCount] = useState(0);
const handleTotal = () => {
setCount((prev) => prev + 1);
}; // --> ํด๋น ์ปดํฌ๋ํธ์์ ์ ์ด๊ถ ํต์
return (
<div className='container'>
<span className='banner'>
Total : {`${count} ${count > 10 ? '๐ฅ' : '๐ชด'}`}
</span>
<div className='counters'>
<Counter total={count} onClick={handleTotal} />
<Counter total={count} onClick={handleTotal} />
</div>
</div>
);
}
import React, { useState } from 'react';
export default function Counter({ total, onClick }) {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount((prev) => prev + 1);
onClick(); // --> ์ฝ๋ฐฑํจ์๋ฅผ props๋ก ์ ๋ฌ
};
return (
<div className='counter'>
<p>
<span className='number'>{count}</span>
<small>/ {total}</small>
</p>
<button className='button' onClick={handleClick}>
ADD
</button>
</div>
);
}
๐ฉ ์ฒ์ ์์ฑํ๋ ์ฝ๋
export default function Counter({ total, setTotalCount }) {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount((prev) => prev + 1);
setTotalCount((prev) => prev + 1); // setState๋ฅผ ๋ฐ๋ก ์ ๋ฌ
};