Search code examples
javascriptangularreduxstore

If a state in my Redux Store is an observable, should I subscribe to it in each component that needs it or subscribe in one place and pass as inputs?


Currently, When a user logs in I subscribe to the user state in my Redux Store in each component that needs the user state.

I want to access the user state in multiple places such as:

  1. the sidebar in my app - to grab a profile pic, userName or ID
  2. Services that needs the user ID to retrieve data from a database

If my user state is an observable should I be subscribing to it in each component and service that needs to know the userID or only subscribing in one place?


Solution

  • Answer has few points:

    You don't need to subscribe to the whole state. You need to subscribe to a specific "slice" of the store using selector createSelector. You can subscribe to it everywhere.

    BUT... few words about good architecture. It is a good practice to split components into two categories: "smart" and "dumb".

    "Smart" - are containers responsible for data resolving and passing it down to children via inputs. Subscribe to state changes here.

    "Dumb" components - are more granular pieces of your app. They should get data via inputs and emit events via outputs. And contain only some specific logic inside.

    This way it will be much easier to have a good structure of the application and to split responsibilities between different parts.