If you are using Redux, and you have an array in state, but you want to prevent duplicate items from making their way into that array, should you prevent duplicates from being added in the array in the reducer or is this something that should be done in an action creator?
-
Although it depends on how much logic you want to put in action creators, I think that the reducer is the obvious choice (since the action still happened, you're just choosing not to mutate the state because of it). Perhaps a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) or an ImmutableJS set would be useful? – Aurora0001 Oct 14 '16 at 19:43
-
1I am just wondering what the best practices are. I think you're right. – Tabbyofjudah Oct 14 '16 at 20:05
1 Answers
Generally, Redux action creators should avoid knowing anything about the application state, as the author of Redux, Dan Abramov, describes:
In general accessing state in action creators is an anti-pattern and you should avoid this when possible.
The best practices for Redux dictate that action creators just create an action to represent that something happened, without considering how that will affect the state. In other words, an action means 'something happened', not 'the state needs to be changed'; it's fine to completely ignore an action if it's not relevant.
On the other hand, a reducer is specifically intended to be a pure function of the previous state and the action, so it is perfectly placed to judge whether an action requires state mutation.
So, in summary, the reducer is probably the best choice, so your action creators can remain 'thin'.

- 1
- 1

- 13,139
- 5
- 50
- 53