1
var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj++)
}
function minus() {
    setBroj(broj--)
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)

when i click first time nothing just after second time work every 2 time ( onclick ) work

Tuzi
  • 160
  • 1
  • 12
  • I'm surprised it works the second time. Doh! I get why now. No re-render means the same `broj` variable is used the second time (and by then it's been updated, by the first click). – T.J. Crowder Mar 20 '21 at 13:44
  • 2
    Does this answer your question? [ReactJS post increment does not work in setState](https://stackoverflow.com/questions/44881217/reactjs-post-increment-does-not-work-in-setstate) – jonrsharpe Mar 20 '21 at 13:45
  • 1
    Side note: Use `const` for what you get from `useState`, not `var` or `let`. That can help you avoid direct mutation (of primitives, anyway). (Side note 2: Never use `var`. It has no place in modern JavaScript. :-) ) – T.J. Crowder Mar 20 '21 at 13:48

3 Answers3

5

When you set the state value with setBroj(broj++) it doesn't change the state with broj + 1 value because ++ affects after the code is executed. You should use setBroj(broj + 1) instead.

var [broj, setBroj] = useState(0);
function plus() {
  setBroj(broj + 1);
}
function minus() {
  setBroj(broj - 1);
}
return (
  <div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
  </div>
);
michael
  • 4,053
  • 2
  • 12
  • 31
3

That's because you're updating state the wrong way. You're mutating the state directly using ++ and -- operators which you shouldn't. Following is the correct way :-

var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj=>broj+1)
    //setBroj(broj+1) - this will also work.
}
function minus() {
    setBroj(broj=>broj-1)
   //setBroj(broj-1) - this will also work.
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
1

This is because you post-increment and post-decrement.

Write setBroj(broj + 1) and setBroj(broj - 1)

Now you could pre-increment and pre-decrement but please don't. You don't need to mutate that variable.

geoffrey
  • 2,080
  • 9
  • 13