dipik
[=]
Story Works Experience Contact Blogs

A compact utility for manage immutable state

24 May, 2023

How do you add element to the array. In JavaScript we have push method, looks very convenient.

const pushResult = projects.push(action.payload)

But this is not allowed in redux state, you should avoid directly mutating the state. To ensure immutability, you should create a new array instead of modifying the existing one. Push method simply mutates the original array by adding one or more elements to the end. The return of push method will be the length of the newly created array. To fix this we have general practiced solution called concat method.

const updatedProjectList = projects.concat([action.payload])

console both the updatedProjectList and projects you can see the difference, concat does not mutate the original array; instead, it returns a new array with the concatenated elements.

But you can find a push statement in official redux official website

todoAdded(state, action) {
    state.push({
        id: action.payload.id,
        text: action.payload.text,
        completed: false
    })
}

This code came under createSlice utility from @reduxjs/toolkit uses the Immer library internally to simplify the process of writing immutable updates.

In German immer means 'always'. A compact utility that streamlines the management of immutable state, enhancing your workflow with greater convenience.

In the example, state.push is acceptable because Immer, used by createSlice, takes care of producing a new immutable state behind the scenes. However, if you were manually modifying the state in a Redux reducer without Immer, you should create a new array to represent the updated state:

author

Author

This is a test user.

Explore

JS
React
Redux

© 2025 DIPIK. All rights reserved.