Managing State with NgRx

NgRx is a tool you can use to control all of the state management in your application. This allows you to have more presentational components, further accelerating the application.

Managing State

As you’ve just seen, handling state in an application can be tricky, especially when it comes time to optimize. In this chapter, you’ll learn about ngrx, a tool you can use to model all of your application states as a series of observable streams.

The application’s state is centralized within ngrx, preventing rogue components from mistakenly modifying the application state. This state centralization gives you precise control over how a state can be modified by defining reducers. If you’ve ever used Redux, a lot of the same patterns apply.

Previously, applications would allow components to modify state without regard for the consequences. There was no concept of a “guard” in place to ensure that this centralized state could only be modified in approved ways.

Dispatched events

ngrx prescribes a set of patterns to bring order to this chaos. Specifically, a component emits a dispatch event when it wants to modify the application’s state. ngrx has a reducer function, which handles how the dispatched event modifies the core state. Finally, the new state is broadcast to subscribers through RxJS.

🙋‍♂️ Joe Asks: That Sounds Really Complicated

While that’s not a question, it’s a good point. State management tools like ngrx do require some forethought and setup. This extra work might not be worth it if you’re just building a simple form page. On the other hand, plenty of big web applications need to change state from many different components, and ngrx fits quite nicely in that case. It’s also important to remember that you don’t need to put everything into your state management system. Sometimes a value is only needed in a single component, and storing the state there is just fine.

Installing ngrx

The first step is to install the basic building blocks of ngrx with npm install @ngrx/core @ngrx/store.

@nrgx/core is required to use any of the tools in the ngrx project. @ngrx/store is the tool you can use to define this central state object and the rules around modifying it.

ngrx has many more utilities, and I encourage you to check them out, but they are outside the scope of this course.

We have already installed the NgRx on our platform for you.

Get hands-on with 1200+ tech skills courses.