setState()
는 컴포넌트의 state
객체에 대한 업데이트를 실행합니다. state가 변경되면, 컴포넌트는 리렌더링됩니다.****
app.js
import React from 'react';
import Counter from './Counter';
function App() {
const onIncrease = () => {
console.log('+1')
}
const onDecrease = () => {
console.log('-1');
}
return (
<div>
<h1>0</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default App;
위와 같은 코드에서 +1버튼과 -1버튼을 만들어 클릭시 각각 함수가 호출되어 console에 +1과 -1이 출력된다.
컴포넌트의 동적인 값을 state라고 한다.여기서 이 동적인 값의 상태 관리를 하기 위해서 useState
를 사용함
import React, { useState } from 'react';
function App() {
const [number, setNumber] = useState(0);
const onIncrease = () => {
setNumber(prevNumber => prevNumber + 1);
}
const onDecrease = () => {
setNumber(prevNumber => prevNumber - 1);
}
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default App;
import React, { useState } from ‘react’;
리액트 패키지에서 useState
를 불러온다.
import React, { useState } from ‘react’;