Angular NgRx Boilerplate Reduction: 2019 Edition

John Youngers
Youngers Consulting
2 min readOct 4, 2019

In 2017 I published this article on reducing NgRx boilerplate:

Back then the NgRx group’s stance was: “when implementing NgRx, you won’t have boilerplate code, you’ll just end up writing the same thing over and over again”

Good news! It’s 2019 and NgRx has some new tools to reduce that not-boilerplate-code: createAction and createReducer

Using the example from the original article, using the new functions (and a small chunk o’ helper code) we can whittle our code down to this:

Where generateFeature takes in the name of the feature as it exists on the state, the initial state of the feature, and an object containing all actions. It then returns an object with the following properties:

  • initialState: centralized reference for use in setting up the module, etc.
  • actions: the same object of actions that was passed into the method
  • selectors: an object containing a selector to pull in the high level feature, as well as selectors to pull in any of the fields at the top level of the state. My state interfaces are generally fairly flat, so this works in my situation, but you can adjust as needed. Note: if you allow undefined for any state properties, they’d to be on your initialState object (as undefinedopposed to being omitted entirely) otherwise this setup won’t work, since it uses the object’s keys.

The use case for UserFeature then becomes:

I’ve only had a chance to play around with the new functions for a few hours, so there’s likely a lot of room for improvement.

I’d like to see how far I can push setting up the actions and correlating them with their associated reducer function, to hopefully make it easier to read, and to remove the chance for any copy paste errors (re-using the same type between actions), but as of now that may be either outside of mine or outside of TypeScript’s skillset.

--

--