Redux State Shape for One-to-Many Relationships

Viewed 1029

When designing a state shape with related entities, the official Redux docs recommend referencing by ID rather than nesting: http://redux.js.org/docs/basics/Reducers.html#note-on-relationships.

In a one-to-many relationship, Normalizr will put the references in the "one" side of the relationship, e.g.:

"posts": {
  "1": {
    ...
    comments: ["1", "2", "3"]
...

Is this better than putting the reference in the "many" side? e.g.

"comments": {
  "7": {
    ...
    postId: "1"
...

Does it matter where I put the reference when creating a Redux store?

1 Answers

I'd suggest keeping the ID of the comments in the post.

This way, for any given post, you can access all the comments by direct reference (index or property name, it doesn't matter), which is fast and easy. That's a complexity of O(N).

In the opposite scenario, you'll have to search your whole comments for any given post. That's a complexity of O(N^2). Plus, you'll have to re-order your comments once you have them all.

Related