import React, { useState } from "react";
const App = () => {
const [count, setCount] = useState(0);
const clickHandler = () => {
setCount(count + 1);
setCount(count + 1);
};
return (
<div>
<h2>{count}</h2>
<button onClick={clickHandler}>증가</button>
</div>
);
};
export default App;
상태 값 변경 함수가 2번 쓰였기 때문에 클릭을 할 때 +2가 한 번에 된다고 생각했다.
ex) 0 => 2 => 4 => 6 => ....
내가 예상했던 거와는 달리 클릭을 할 때 마다 +1이 된다.
ex) 1 => 2 => 3 => 4 => ....
import React, { useEffect, useState } from "react";
const App = () => {
const [count, setCount] = useState(0);
const clickHandler = () => {
setCount(count + 1);
setCount(count + 1);
};
useEffect(() => {
window.addEventListener("click", clickHandler);
return () => window.removeEventListener("click", clickHandler);
});
return (
<div>
<h2>{count}</h2>
<button onClick={clickHandler}>증가</button>
</div>
);
};
export default App;
리액트 내부에서 관리가 되지 않기 때문에 배치로 처리가 되지 않는다.