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?
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With