Is using getState in Redux an anti-pattern?

后端 未结 1 1065
轮回少年
轮回少年 2021-01-12 14:26

I\'m using Redux for the first time in a jQuery application and I have created small observable implementation. The observables are responding to changes on multiple propert

1条回答
  •  隐瞒了意图╮
    2021-01-12 14:40

    When you use store.getState() too liberally, you end up passing around the global state to random components. You run the risk of introducing coupling between components and parts of your state that have nothing to do with one another, which is anti-pattern. You should only call getState for two reasons: to fetch the initial state of the app, and in the update logic for your store -i.e inside your store.subscribe() callback.

    As far as your observables go, in a typical component based view layer such as React, the only thing you really need to observe in a redux app is the entire application state as a whole, not individual pieces of it. Changes to the state as a whole are subscribed to and trickle down from the top level component.

    However since you are refactoring a Jquery application I think your use of observables is acceptable. There is a library called reselect that you can use for this purpose if you don't feel like rolling your own. It helps you to compute state from arbitrary parts of the global state and provides efficient memoization so same inputs don't get recomputed.

    At times, I realize I need a specific state property in a piece of code that I may not have the time to properly refactor into an observable. In those instances, I call getState on the store to get what I need and move on with it. I can't help feeling like this approach is a little flawed.

    One easy drop-in solution you could implement in cases like this is to use event emitters in your reducers to propagate pieces of the global state to the specific Jquery components that need them. This will keep you from having to pass around global state, preserving component isolation.

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