Redux - Why normalize?

后端 未结 2 1343
借酒劲吻你
借酒劲吻你 2021-02-02 14:15

I have been trying to learn how to better structure my Redux stores and stumbled upon this lesson by Dan.

https://egghead.io/lessons/javascript-redux-normalizing-the-sta

相关标签:
2条回答
  • 2021-02-02 14:21
    1. "In complex apps, we might have more than a single array and todos with the same IDs in different arrays might get out of sync."

    You may have a TODO (say with id 1) which is in a "User's TODOs" list and a "Department's TODOs" list at the same time, for example. And then if a user updates her todo, that TODO should also be updated in the "Department's TODOs" list. If your data is normalized, the TODO will be updated in both places (well, there will really only be one instance of the TODO which is simply referred to from multiple places). But if it's not normalized, the department will have a stale copy of the todo.

    1. "Why keep a list of all ids?"

    I think you're right, honestly. If you're going to bother normalizing, then duplicating a list of IDs kind of seems to run counter to that effort.

    Anyway, I think the case for normalizing data in React probably mirrors the case for normalizing data in general (e.g. in databases). It's a bit more effort up front, but the flexibility it gives you is generally worth it.

    Also, I don't always normalize my React code, but I find that not normalizing ends up making my code sloppier over time. I just become less disciplined. I guess it's like the broken-window effect. In non-normalized code, I just start throwing values into places they really probably shouldn't be simply out of convenience.

    0 讨论(0)
  • 2021-02-02 14:39

    Why do we need to maintain a list of allIds? Why maintain this additional state, when we can easily map over the list of all todos and obtain it?

    Storing an array of IDs allows us to define an order for the items. While JS engines now have a fairly standardized process for iterating across keys in an object, you shouldn't rely on that to define ordering.

    Answer thanks to markerikson

    0 讨论(0)
提交回复
热议问题