React.useState의 기본
function App() {
const [counter, setCounter] = React.useState(0);
const onClick = () => {
// setCounter(counter + 1);
setCounter((current) => current + 1);
};
return (
<div>
<h3>Total clicks: {counter}</h3>
<button onClick={onClick}>Click Me</button>
</div>
);
}
useState()는 [variable, modifierFunction]을 제공한다.
useState()의 괄호 안에는 default value를 지정할 수 있다.
default value를 지정할 경우 variable의 기본 값으로 사용된다.
modifierFunction을 이용해 variable의 값이 변경되도록 사용될 때 알아서 rendering을 다시 하게된다.
modifierFunction((current) => current + 1)처럼 사용하는 것이 더 안전한데, 그 이유는 실제 어플리케이션에서 variable의 값이 다른 곳에서 변경될 수 있기 때문이다. 그래서 함수가 사용되는 시점에서의 현재 값을 가지고 변경을 하도록 한다.