
๐ก๋ ธ๋ง๋์ฝ๋ ๋๊ผฌ์ค์ ๊ฐ์๋ฅผ ๋ณด๋ฉฐ ๊ณต๋ถํ๋ ์๋ฆฌ์ฆ์ ๋๋ค.
React์ state
state๋ ๋ฐ์ดํฐ๊ฐ ์ ์ฅ๋๋ ๊ณณ์ ๋งํ๋ค. ์ด๋ฒ ํฌ์คํ
์์๋ react์์ ๊ฐ์ด ๋ฐ๋๋ ๋ฐ์ดํฐ๋ฅผ ์ด๋ป๊ฒ ๋ด์์ค ์ ์๋์ง ๋ณต์ตํ๋ค.
์ด์ ํฌ์คํธ์์ ๊ตฌํํ๊ณ ์ ํ๋ ๊ธฐ๋ฅ์ด๋ค.
jsx๋ฌธ๋ฒ์ผ๋ก component๋ฅผ ๋ง๋ค๊ณ ReactDOM์ ์ด์ฉํด html body์ ๋์๋ค.
const root = document.getElementById("root");
const Title = () => {
// arrow function์ผ๋ก ๋ณ๊ฒฝํด์ฃผ์๊ณ , ํ์๊ฐ์ธ return์ ์ถ๊ฐํด์ฃผ์๋ค.
return (
//return ์์ jsx์ฝ๋๋ฅผ ์์ฑํ๋ค.
<h3 id="title" onMouseEnter={() => console.log("i am mouse enter")}>
Hello, i am title
</h3>
);
};
const Btn = () => {
return (
<button onClick={() => console.log("i am clicked")}>Click me</button>
);
};
const Container = <div><Title/> <Btn/></div>;
//Title, Btn์ ์ปดํฌ๋ํธํ ๋์ด container์์ ๋ค์ด๊ฐ ์ ์๋ค.
๐ฉ๐ปโ๐component๋ฅผ ๋ง๋ค๋ ๋ณ์์ ์ฒซ๋ฌธ์๋ ๋ฌด์กฐ๊ฑด ๋๋ฌธ์๋ฅผ ์ฌ์ฉํด์ผํ๋ค.
const root = document.getElementById("root");
let counter = 0;
function countUp() {
counter = counter + 1;
}
const Container = () => (
<div>
<h3>Total clicks: {counter}</h3>
<button>Click me</button>
</div>
);
ReactDOM.render(<Container />, root);
์ด๋ ๊ฒ ์ฝ๋๋ฅผ ์ง๊ฒ ๋ ๊ฒฝ์ฐ ๋ธ๋ผ์ฐ์ ์์๋ ๋ณํ๊ฐ ์์ง๋ง ์ฝ์์์๋ ํด๋ฆญํ ๋งํผ counter๊ฐ +1๋ ๊ฒ์ ๋ณผ ์ ์๋ค.

์ ๋ธ๋ผ์ฐ์ ์๋ update๊ฐ ๋์ง ์์๊ฑธ๊น?
react๊ฐ ๋ ๋๋ ๋, ReactDOM์ด ๊ฐ์ฅ ๋จผ์ ์คํ๋๊ณ ์ดํ ๋ค์ ์ฌ์คํ์ด ๋์ง ์์๊ธฐ ๋๋ฌธ์ด๋ค.
๊ทธ๋ฌ๋ฏ๋ก function countUp์ด ์คํ๋ ๋ ๋ค์ ํ๋ฒ ReactDOM์ ์คํํด์ผ ๋ธ๋ผ์ฐ์ ์์๋ state๊ฐ update๋๋ ๊ฒ์ด๋ค. ์ด๊ฒ์ UI update๋ผ๊ณ ํ๋ค.
const root = document.getElementById("root");
let counter = 0;
function countUp() {
counter = counter + 1;
ReactDOM.render(<Container />, root);
}
const Container = () => (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={countUp}>Click me</button>
</div>
);
ReactDOM.render(<Container />, root);
ํจ์ counter๊ฐ ์คํ๋ ๋ ReactDOM์ ์ฌ์คํํ๋ ๋ธ๋ผ์ฐ์ ์ update๋ state๊ฐ ๋ณด์ฌ์ง๋ค.

๋ง์ฝ ๋ ๋ํด์ผํ๋ ์ํฉ์ด ๋ง์์ง๋ค๋ฉด ์ด๋ป๊ฒ ํด์ผํ ๊น?
ReactDOM.render... ๋ฐ๋ณต์ ์ผ๋ก ์ฝ๋๋ฅผ ์ฐ๋ ๊ฒ์ ๋นํจ์จ์ ์ด๋ค.
์ด๋๋ ํจ์๋ก ๋ง๋ค์ด ์ฌ์ฌ์ฉํ๋ ๊ฒ์ด ํจ์จ์ ์ด๋ค.
const root = document.getElementById("root");
let counter = 0;
function countUp() {
counter = counter + 1;
render();
}
function render() {
ReactDOM.render(<Container/>, root);
}
const Container = () => {
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={countUp}>Click me</button>
</div>
);
};
render();

๊ฒฐ๊ณผ๋ ๋์ผํ๊ฒ ์ถ๋ ฅ๋๋ค.
์ฌ๊ธฐ์ ์กฐ๊ธ ๋ ๋ฐ์ ์ํจ๋ค๊ณ ํ๋ฉด, javascript์ ์ฐ์ฐ์์ธ ++๋ฅผ ํ์ฉํ๋ ๋ฐฉ๋ฒ์ด ์๊ฒ ๋ค.
const root = document.getElementById("root");
let counter = 0;
function countUp() {
counter++;
render();
}
function render() {
ReactDOM.render(<Container />, root);
}
const Container = () => {
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={countUp}>Click me</button>
</div>
);
};
render();
โ๐ป์ด๋์ react ์ฐ๋๊ตฌ๋โจ
vanilla์์๋ ์ ์ฒด๊ฐ ์๋ก ์์ฑ๋์ง๋ง react์์๋ ๋ณ๊ฒฝํ state๋ง update๋๋ค.

์ดํด ์์ ์ค๋ช
์ ๋ฐ๊ฒฌํด์ ์ถ๊ฐ!
