4

This is a question about state in Redux js. I have an array list in the state:

{
  list: list
}

According to Redux document, I should not modify the state in the reducer. I want to append a new item to the list. Should I clone the list, or simply append the new item to the list:

let newList = state.list;
newList.push(newItem);
return {
  list: newList
}

The above code actually modify the original state, because the newList is the same list as "state.list". Is this an OK practice, or should I use immutableJS to clone the list?

2 Answers 2

11

You are mutating the list here and giving back the same reference. I believe something like below should make a new copy

return { list: [...state.list, newItem] }

It's not mandatory to use immutableJS. but you need to make sure not to mutate the state.

take a look at deep-freeze library to make sure that your state is not being edited.

this video from Dan (creator of redux) should help as well

Sign up to request clarification or add additional context in comments.

Comments

3

If you aren't keen on the spread operator, you can also do:

var newList = list.slice(); // copy the array
newList.concat(['item']);
return {
  list : newList
}

1 Comment

In fact Array#concat behaves in an immutable fashion. It returns a new array whilst leaving the initial one as is. So not only is it unnecessary to create a copy of the array, the above code will fail because you haven't assigned the return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.