I’m starting my React journey and I’m facing something strange. I already understood that I shouldn’t mutate the state 🙂
However, I’d like to know why the following code causes the counter to increase by 2 (e.g. 1,3,5,7,9, etc.)
import { useState } from 'react' import './App.css' function App() { const [state, setState] = useState({ count: 0 }) return ( <> <button onClick={() => setState((state) => { state.count++; return {...state}; })}> count is {state.count} </button> </> ) } export default App
<StrictMode>enabled? If so it is indicating your mutation of state as expected. Instead update state appropriatelyreturn {...state, count: state.count + 1};and remove the mutating linestate.count++;