Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux State Shape for One-to-Many Relationships

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?

like image 241
miljinx Avatar asked Oct 05 '17 04:10

miljinx


People also ask

Should I keep all component's state in Redux store?

Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state. Using local component state is fine.

Can Redux state be an array?

In React and Redux it's said to keep the state immutable. It simply means that we should not change the state properties directly. Here I'll show a few ways how we can update a state array in a redux reducer as it can be little overwhelming if you are new to redux.

What pattern for single file logic is recommended by Redux?

Within a given feature folder, the Redux logic for that feature should be written as a single "slice" file, preferably using the Redux Toolkit createSlice API. (This is also known as the "ducks" pattern).

How do I organize my Redux reducers?

At its core, Redux is really a fairly simple design pattern: all your "write" logic goes into a single function, and the only way to run that logic is to give Redux a plain object that describes something that has happened.


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.

like image 59
Julien Bérubé Avatar answered Jan 02 '23 09:01

Julien Bérubé