Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
Post Closed as "Duplicate" by Phil javascript
added 86 characters in body
Source Link
WSD
  • 3.7k
  • 35
  • 48

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 })

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 

}

export default App

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

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 
Source Link

Why does count increment by 2 in this React setState updater function?

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