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
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
Share Improve this question edited Mar 20, 2021 at 13:44 Tuzi asked Mar 20, 2021 at 13:42 TuziTuzi 1601 gold badge1 silver badge14 bronze badges 3-
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 Commented Mar 20, 2021 at 13:44 - 2 Does this answer your question? ReactJS post increment does not work in setState – jonrsharpe Commented Mar 20, 2021 at 13:45
-
1
Side note: Use
const
for what you get fromuseState
, notvar
orlet
. That can help you avoid direct mutation (of primitives, anyway). (Side note 2: Never usevar
. It has no place in modern JavaScript. :-) ) – T.J. Crowder Commented Mar 20, 2021 at 13:48
3 Answers
Reset to default 5When 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>
);
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>
)
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.