헉!!/javascript
[React] State
권태성
2024. 7. 21. 00:08
State를 사용하려면 React를 import 해줘야함
import React,{useState} from "react";
컴포넌트는 상태가 변화하면 화면을 다시 그리는 Re-rendering 과정을 거친다.
그에 따라 해당 함수가 다시 호출된다.
컴포넌트는 State를 여러개 가질 수 있다.
import React, { useState } from "react";
const Counter = () => {
//0에서 출발
//1씩 증가
//1씩 감소
//[상태의값, 상태변화메소드] = 함수(초기값);
const [count, setCount] = useState(0);
const onIncrease = () => {
setCount(count + 1);
};
const onDecrease = () => {
setCount(count - 1);
};
const [count2, setCount2] = useState(0);
const onIncrease2 = () => {
setCount2(count2 + 1);
};
const onDecrease2 = () => {
setCount2(count2 - 1);
};
return (
<div>
<h2>{count}</h2>
<button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button>
<h2>{count2}</h2>
<button onClick={onIncrease2}>+</button>
<button onClick={onDecrease2}>-</button>
</div>
);
};
export default Counter;
728x90