Search code examples
reactjsreduxreact-reduximmutabilityredux-toolkit

Redux : assigning new value to state in reducer doesn't update state but mutating works


In this code, when i change the value of state in the setMessage() reducer to action.payload, the changes aren't getting picked up by the selectors.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: null,
  type: null
}

export const messageSlice = createSlice({
  name: 'message',
  initialState: initialState,
  reducers: {
    setMessage: (state, action) => {
      state = action.payload                         //not working
    },
    clearMessage: state => {
      state = initialState                           //not working
    }
  }
})

but if i change the "value" or "type" field of the message state instead of changing the whole object, the selectors are able to pick up the changes and everything works fine:

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: null,
  type: null
}

export const messageSlice = createSlice({
  name: 'message',
  initialState: initialState,
  reducers: {
    setMessage: (state, action) => {
      state.value = action.payload.value           //works
      state.type = action.payload.type             //works
    },
    clearMessage: state => {
      state.value = null                           //works
      state.type = null                            //works
    }
  }
})

Solution

  • There are no pointers in JavaScript. When = is used with a variable a new value is assigned to it, not to a memory address

    function setMessage(state) {
      state = {
        x: 5
      }
    }
    
    let state = {
      x: 3
    }
    setMessage(state)
    
    console.log(state)

    function setMessage(state) {
      state.x = 5
    }
    
    let state = {
      x: 3
    }
    setMessage(state)
    
    console.log(state)