Understanding computed property names in Redux Toolkit extraReducers

I’m working through the Redux Toolkit documentation and came across something confusing in the createSlice function. Here’s the code example I’m looking at:

const addValue = createAction('addValue')

createSlice({
  name: 'total',
  initialState: 0,
  reducers: {},
  extraReducers: {
    [addValue]: (state, action) => {
      return state + action.payload
    },
    'another/action/type': (state, action) => {},
  },
})

I’m confused about the bracket notation being used here. What does [addValue] mean in this context? I understand using strings as keys, but why are we wrapping the action creator in square brackets? Is this some kind of array syntax or something else entirely? Any explanation would be really helpful.

The bracket notation you see, like [addValue], is a feature of JavaScript known as computed property names. This allows you to dynamically use the value of a variable as the key for an object. In your case, addValue represents an action creator that has a type associated with it. Using the brackets means when this code executes, JavaScript will obtain the type of addValue and use it as the key for the reducer function. This provides better maintainability since if the action type needs to change, you only have to modify it in one place. This avoids hardcoded strings and potential typos, leveraging the robustness of action creators.

totally! the [addValue] is just js letting you use the value of addValue as the key, super handy. it’s like, instead of hardcoding strings, you get less errors and way more clarity when you might change action types later. def recommend it!

Yeah, this trips up tons of people when they’re starting with Redux Toolkit. Those square brackets are just JavaScript’s computed property syntax - it’s been around since ES6. When you write [addValue], JavaScript looks at what’s inside the brackets and uses that as the object key. Since addValue comes from createAction, it has a .type property that gets converted to a string automatically. So [addValue] becomes [addValue.type], which is whatever string you passed to createAction. Way cleaner than typing out action strings manually - no typos, and refactoring is a breeze. Change the action type once and it updates everywhere.