2

One of our developers suggested it is preferable to not use classes to construct redux store, but didn't give a concrete reason, mostly saying "it is not idiomatic and classes are not that well-implemented in ES6; it is preferable to avoid using classes in React".

Are there any issues (even if it's actually not an industry-standard?) to construct a redux store in this manner?

class Item {
  public name: string;
}

class ItemState {
  public items: Item[];
  public currentItem: Item;
}

// redux store
class AppState {
  public Items = new ItemState();
}

// then createStore(/*reducer*/, new AppState())

2 Answers 2

2

One thing that comes to mind is serialization. If you want to support things like hydration and time-travel debugging you need to be able to serialize your store and restore it.

Your example class doesn't use any methods or inheritence, so maybe that's not an issue for you. But if you plan to add that stuff, be aware that you may be cutting yourself off from the features i mentioned.

See also this section of the redux documentation

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

1 Comment

Yeah, I realize the classes need to be pure DTOs with no behavior. I can declare them to be interfaces or types with little changes, technically.
0

In my limited experience... I have not used classes in this way, but I have used complex Objects as part of my redux store. By complex objects I mean some of my state variables are objects with different properties and arrays of other objects in them. They work, so I see no reason why classes would not. But I would advise to avoid it if at all possible, as it may make accessing state more confusing as the app grows. Note that when you connect a Component that needs to acces the currentItem's name you will have to write:

function mapStateToProps(state)
{
   return {currentItemName: state.Items.currentItem.name};
}

That seems too long to me. Even if you pass state.Items directly to your component, at some point you will need to access the currentItem's name and need to write the fully qualified name. I think the choice mostly depends on the particular aspects of the app. But as I said, my experience is limited, and I have made my redux stores using classes yet.

Comments

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.