0

I have a simple useReducer increment counter.

import {useReducer} from 'react'



const counterStateFn =  (state,action) => {
 if(action.type === "INCREMENT") {
     return {count : state.count++}
 }
 if(action.type === "DECREMENT") {
    return {count : state.count--}
}
 return {count: 0}
}

const Counter = () => {

    const [counterState, modifierCounterState] = useReducer(counterStateFn,{count: 0});
    
   

    const modifierCounterStateIncrementFn = () => {
        modifierCounterState({type:"INCREMENT"});
    }


    const modifierCounterStateDecrementFn = () => {
        modifierCounterState({type:"DECREMENT"})
     }

    return (
        <div className="counter-wrap">

            <button onClick={modifierCounterStateIncrementFn}>Increment(+)</button>
            <span>Count is: {counterState.count}</span>
            <button onClick={modifierCounterStateDecrementFn}>Decrement(-)</button>
        </div>
    );
}

export default Counter;

Inside counterStateFn I use {count : state.count++} and {count : state.count--} to increment and decrement the counter and this doesn't work.

If I use {count : ++state.count} or {count : state.count+1} it will work.

I would like to know why {count : state.count++} and {count : state.count--} doesn't work.

Thankyou.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Rejin Jose
  • 41
  • 6

2 Answers2

1

As noted at its docs, the Increment (++) operator, if used as postfix, it increments and returns the value BEFORE incrementing.

While you want the value AFTER incrementing in order to trigger a state change.

You can check it by yourself in Devtools:

x = 5;
x++ // returns 5

y = 5;
++y // returns 6
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

As pointed by Dennis x++ operator returns value and then increments.

To fix your problem you can either use ++count or count + 1.

const counterStateFn =  (state,action) => {
 if(action.type === "INCREMENT") {
     return {count : state.count + 1}
 }
 if(action.type === "DECREMENT") {
    return {count : state.count - 1}
}
 return {count: 0}
}
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37