If you’re working with NGRX, you might be familiar with the concept of actions. In most cases, actions are treated as commands – they instruct the application to do something. However, there’s a better way to use actions that aligns better with the NGRX architecture: treating them as events.
The Benefits of the NGRX Architecture
The NGRX architecture follows a unidirectional flow that’s easy to reason about. When a user interacts with a component, it dispatches an action that updates the store. The updated store triggers a reactive update to any subscribed components, which display the new data. This architecture makes it easy to debug and maintain the code.
The Pitfalls of Using Actions as Commands
When you use actions as commands, it’s easier to break the unidirectional flow of the NGRX architecture. You might reuse an action in a different place, chain actions together, or skip the store altogether and set actions in a service. All of these actions make the code harder to reason about and maintain.
Embracing Actions as Events
When you treat actions as events, you enforce better usage of the NGRX architecture. Instead of thinking about what the action should do, you focus on what has happened. This shift in thinking makes it easier to maintain the unidirectional flow of the architecture.
How to Use Actions as Events
If you want to embrace actions as events, your components should only dispatch one action. That action should represent the event that occurred, such as a button click. If you need to do different things depending on the event, you can add an immediately boolean to the action payload. Then, you can write reducers and effects with this parameter in mind.
Conclusion
By treating actions as events instead of commands, you can maintain the unidirectional flow of the NGRX architecture. This makes it easier to reason about and maintain the code. So, next time you’re working with NGRX, try embracing events and see how it improves your code!