Christian Christian - 1 year ago 79
Javascript Question

Adding functions to redux store within reducer is an anti pattern?

say I have a component connected to the redux store. Within this store, there's a list of objects. For instance something like this:

ReduxStore: {
dataList: [

Is it actually an anti pattern to create and add a filter function within the reducer to create something like this:

ReduxStore: {
dataList: {
isNameAvailable: (name) => {/* search for name */}

It works great, but I'm not sure whether this was the intended way to go.

Answer Source

It's an anti-pattern because your store only cares about data, not computation. Once you start adding functions to your store, you lose the ability to serialize the data inside it.

However, it's pretty trivial to pull these kinds of helper functions out and turn them into standalone utility selectors which you can use to achieve the same thing.

function isNameAvailable(store, name) {
  /* search for `name` in `store` */

Now the function works independently of the store and you can keep them separate for testing.

From here, you can take a look at Reselect which allows you to turn your isNameAvailable function into a cached selector, meaning you'll only need to re-calculate as and when the appropriate data in the store is changed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download