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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With