Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Redux, Am I mutating state here?

I am playing around with a simple React Redux app that increments a counter each time a button is clicked. I am testing two different methods of incrementing my counter in my Redux Reducer. Both methods are changing the state in the reducer however one of these methods is not causing my counter to rerender.

Here is the reducer which will cause the page to rerender:

const reducer = (state={speed: 0}, action) => {

  if(action.type ==='INCREMENT_SPEED'){
    state = {...state, speed: state.speed+=1 
    }
    return state 
}

and here is the code that functions but will not cause the page to rerender with the proper value.

const reducer = (state={speed: 0}, action) => {

      if(action.type ==='INCREMENT_SPEED'){
        state.speed++ 
    }
    return state 
}

The only difference is the way in which I am updating state. My guess is that using the ++ incrementer is actually mutating state which is not seen as a change and hence does not cause the page to render.

If it helps here is the part of the code that appends to the DOM:

render() {
    return (
      <div>

        <p>SPEED: {this.props.reduxState.reducer.speed}</p>

      </div>
    )
  }
}
like image 460
tdammon Avatar asked Jan 28 '26 13:01

tdammon


1 Answers

You're correct in your assumption. In the second example you're mutating the state and that will not trigger a re-render. You should never mutate the state. Always make a copy of the state and return a new state.

like image 88
weibenfalk Avatar answered Jan 31 '26 02:01

weibenfalk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!