0

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 
5
  • 1
    You are directly modifying the state.count by incrementing it, but you should never mutate state directly in React. Commented Oct 10, 2023 at 21:39
  • 2
    Do you have <StrictMode> enabled? If so it is indicating your mutation of state as expected. Instead update state appropriately return {...state, count: state.count + 1}; and remove the mutating line state.count++; Commented Oct 10, 2023 at 21:45
  • see: Does strict mode work differently with React 18? for further discussion of what actions are run twice in strict mode. Commented Oct 10, 2023 at 21:51
  • @pilchard yeah, I know that already. My question is not about how to “fix” it but to understand, the reason why the counter is increased by 2. I’m looking for some explanations about what is React doing behind the scenes which causes the setState function to run twice Commented Oct 10, 2023 at 21:54
  • 3
    Read the linked post on how StrictMode works. Your specific mutation won't show up in production (or if you remove StrictMode) but in development StrictMode runs functions passed to useState twice, so your mutation is run twice and you see it incremented by 2. If you remove the mutating statement as recommended above you'll see it increment by 1 as expected. Commented Oct 10, 2023 at 21:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.