State Management Pitfalls to Avoid: NgRx and Angular
Sharing some lessons I have learned after having worked with NgRx for a while now.
--
Background
Building web applications with state is a complex and ever-changing area. Managing state in Angular applications can be a tricky task.
NgRx is a popular state management library for Angular apps, but it can be difficult to use correctly.
To help fellow engineers avoid common pitfalls, I have laid out some key tips for working with NgRx state management in Angular apps.
1) Ensure that all components in the application are properly connected to the store
This can be achieved by using the @Select decorator to connect components to store observables or by using the store.pipe() operator.
This will ensure that changes to the store are properly reflected in the UI.
2) Avoid mutating state directly
5/28/2023 Edit: I’ve recently learned that the state is no longer mutable from the components, and with more recent versions of NgRx is a frozen object that can be updated only from the reducers via pure functions. And with every state mutation a new copy is created.
Special thanks and kudos to Klajdi Avdiaj for taking the time out in mentioning that to me in the comments. 🙂 Please feel free to check out his Medium page to learn more about Angular development!
3) Ensure that all actions have a corresponding reducer
NgRx actions are dispatched to the store, and reducers are responsible for updating the state.
Without appropriate reducers, action dispatches will not be processed and the state will not be updated.
4) Use the NgRx entity adapter when dealing with collections of data
This will provide a consistent interface for working with collections, and it can also improve performance when dealing with large amounts of data.
5) Keep state as normalized as possible
This means that each piece of data should only be represented once in the store.
This will reduce complexity and improve performance when dealing with large datasets.
Closing
Thanks for reading along! 🙂
By following these 5 quick tips, engineers can avoid common pitfalls when using NgRx state management in their Angular applications.