React/한입 크기로 잘라 먹는 리액트(React.js)
5-4. State(상태) (React State)
ddo_0ii
2022. 7. 1. 10:26
State - 계속해서 변화하는 특정 상태 상태, 상태에 따라 각각 다른 동작을 함
컴포넌트의 state가 변경이 되면, 그 컴포넌트는 rerender가 된다.
// 상태 사용하겠다.
import React, { useState } from "react";
const Counter = () => {
console.log('호출');
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;