Reputation: 395
I started to learn better redux + reactjs
For example I have a news or list reducer that should return an array contain news items :
const list = [
{id: 1, title: 'One'},
{id: 2, title: 'Two'},
{id: 3, title: 'Three'}
]
export function newsReducer(state = [], action) {
switch (action.type) {
case 'GET_NEWS':
return list
default:
return state
}
}
This code works right, but in other articles I saw they passed parameters with [...state, ...] and immutable format ...
So can I pass parameters simple or I should pass in immutable format ?
Thanks
Upvotes: 7
Views: 11012
Reputation: 8274
In short: Yes you can pass simple arrays in if that suits your needs best.
If you are going to use a simple array, then make sure to return a new array when making modifications.
For example:
export function listChangeReducer = (state = [], action) => {
switch action.type {
case 'ADD_ITEM':
// don't do this because you're mutating your state
// state.push(action.item);
// instead do this
state = state.slice();
state.push(action.item);
// or alternatively you can use the destruct syntax
//[...state, action.item];
return state;
break;
}
};
You aren't required to use immutablejs data structures with redux. It is just recommended so that you don't accidentally mutate your data structures.
The documentation states that the data needs to be immutable because
Both Redux and React-Redux employ shallow equality checking. In particular:
Redux's combineReducers utility shallowly checks for reference changes caused by the reducers that it calls.
Upvotes: 7