All Blogs

Introduction to NgRx Slice

In this blog post, I want to introduce my latest open source project [ngrx-slice](https://github.com/nartc/ngrx-slice).

TLDR

Run the following command to install:

Terminal window
1
npm install ngrx-slice ngrx-immer immer

What is ngrx-slice?

ngrx-slice is an NgRx plugin that provides almost the same functionalities that Redux Toolkit createSlice provides.

At this point, some of you might then ask “Hm… Chau, so what is createSlice then?” createSlice is dubbed, by Mark Erikson aka the author, as the modern way of implementing Redux in your JavaScript application, especially in ReactJS. The idea is to group most, if not all, Redux-related building blocks into a single slice of the global state. A slice has multiple layers which kind of represent multiple building blocks of a piece of State: Actions, Reducers, and Selectors.

Let’s take a look at the following Counter example in vanilla Redux:

1
// Actions
2
const increment = { type: "increment" };
3
const decrement = { type: "decrement" };
4
5
// reducers
6
const initialState = {
7
value: 0,
8
};
9
10
const reducer = (state, action) => {
11
switch (action.type) {
12
case "increment":
13
return { ...state, value: state.value + 1 };
14
case "decrement":
15
return { ...state, value: state.value - 1 };
16
default:
17
return state;
18
}
19
};
20
21
// selectors
22
const selectValue = (state) => state.counter.value;

Note that Actions, Reducers, and Selectors can be (and most of the time recommended) separated out into different files. So you might have: counter/actions.js, counter/reducer.js, and counter/selectors.js

Now let’s look at the same example with createSlice API:

1
const counterSlice = createSlice({
2
name: "counter",
3
initialState: {
4
value: 0,
5
},
6
reducers: {
7
increment: (state) => {
8
// Redux Toolkit allows us to write "mutating" logic in reducers. It
9
// doesn't actually mutate the state because it uses the Immer library,
10
// which detects changes to a "draft state" and produces a brand new
11
// immutable state based off those changes
12
state.value++;
13
},
14
decrement: (state) => {
15
state.value--;
16
},
17
},
18
});
19
20
export default counterSlice.reducer;
21
export const { increment, decrement } = counterSlice.actions;
22
23
export const selectValue = (state) => state.counter.value;

To learn more about this createSlice API, please refer to Redux Toolkit createSlice

You can already notice the amount of code is much less in createSlice version with Actions being generated from the Reducers. Coupled with Immer for simpler state updates, the boilerplate becomes manageable.

ngrx-slice embraces this same idea, but for NgRx

Why?

The main goal of ngrx-slice is an attempt to reduce the amount of boilerplate of NgRx, at least for simpler features. A by-product goal of ngrx-slice is to ease the learning curve to NgRx for React developers who now work with Angular and NgRx.

Imagine having the ability to reduce the following code (Counter example with NgRx):

1
export const increment = creaeteAction("[Counter] Increment");
2
export const decrement = createAction("[Counter] Decrement");
3
// putting in some effect just to make a point
4
export const multiplyBy = createAction(
5
"[Counter] Multiply By",
6
prop<{ multiplier: number }>(),
7
);
8
export const multiplyBySuccess = createAction(
9
"[Counter] Multiply By Success",
10
prop<{ value: number }>(),
11
);
1
export interface CounterState {
2
value: number;
3
incrementCount: number;
4
decrementCount: number;
5
}
6
7
export const initialState: CounterState = {
8
value: 0,
9
incrementCount: 0,
10
decrementCount: 0,
11
};
12
13
export const counterReducer = createReducer(
14
initialState,
15
on(increment, (state) => ({
16
...state,
17
value: state.value + 1,
18
incrementCount: state.incrementCount + 1,
19
})),
20
on(decrement, (state) => ({
21
...state,
22
value: state.value - 1,
23
decrementCount: state.decrementCount + 1,
24
})),
25
on(multiplyBySuccess, (state, { value }) => ({ ...state, value })),
26
);
1
export const selectCounter = createFeatureSelector<CounterState>("counter");
2
export const selectValue = createSelector(
3
selectCounter,
4
(state) => state.value,
5
);
6
export const selectIncrementCount = createSelector(
7
selectorCounter,
8
(state) => state.incrementCount,
9
);
10
export const selectDecrementCount = createSelector(
11
selectorCounter,
12
(state) => state.decrementCount,
13
);

The following effect is included for completeness. ngrx-slice does not affect how you write your Effects.

1
@Injectable()
2
export class CounterEffects {
3
constructor(
4
private store: Store,
5
private actions$: Actions,
6
) {}
7
8
readonly multiplyBy = createEffect(() =>
9
this.actions$.pipe(
10
ofType(multiplyBy),
11
concatLatestFrom(() => this.store.select(selectValue)),
12
// switchMap to a mock side-effect (timer)
13
switchMap(([{ multiplier }, currentValue]) =>
14
// delay 1s to simulate async task
15
timer(1000).pipe(
16
map(() => multiplyBySuccess({ value: currentValue * multiplier })),
17
),
18
),
19
),
20
);
21
}

The above snippets are pretty standard in NgRx world. Most of the time, you will have all of those files for each of your feature states. And to be honest, it does feel a bit overwhelming, especially for NgRx beginners. Let’s explore how ngrx-slice can help with this.

How?

Installation

Like most things JavaScript/TypeScript, we start with installing ngrx-slice

Terminal window
1
npm install ngrx-slice ngrx-immer immer

ngrx-slice depends on ngrx-immer and immer to allow for simpler state updates, just like createSlice

Implementing the Slice

Instead of the 3 different files for Actions, Reducers, and Selectors, you’d have a Slice file.

1
export interface CounterState {
2
value: number;
3
incrementCount: number;
4
decrementCount: number;
5
}
6
7
export const initialState: CounterState = {
8
value: 0,
9
incrementCount: 0,
10
decrementCount: 0,
11
};
12
13
export const {
14
selectors: CounterSelectors,
15
actions: CounterActions,
16
...CounterFeature
17
} = createSlice({
18
name: "counter",
19
initialState,
20
reducers: {
21
increment: (state) => {
22
state.value++;
23
state.incrementCount++;
24
},
25
decrement: (state) => {
26
state.value--;
27
state.decrementCount++;
28
},
29
multiplyBy: {
30
trigger: noopReducer<CounterState, { multiplier: number }>(),
31
success: (state, { value }: PayloadAction<{ value: number }>) => {
32
state.value = value;
33
},
34
},
35
},
36
});

createSlice, noopReducer(), and PayloadAction are imported from ngrx-slice

That’s all. Just like Redux Toolkit’s createSlice, ngrx-slice accepts a SliceOptions object and returns the Reducer, generated Actions, and in addition the Selectors. For a more detailed explanation, please check out ngrx-slice Documentations

Using the Slice

The return value of createSlice is an object with the shape { actions, selectors, name, reducer }. With destructuring, CounterFeature here is actually an object of { name, reducer }, which is compatible with StoreModule.forFeature()

1
@NgModule({
2
imports: [
3
/* ... */
4
// before: StoreModule.forFeature({ name: 'counter', reducer: counterReducer })
5
StoreModule.forFeature(CounterFeature),
6
EffectsModule.forFeature([CounterEffect]),
7
/* ... */
8
],
9
declarations: [CounterComponent],
10
})

CounterSelectors and CounterActions are just namespacing the generated Actions and Selectors. With this, counter.effect.ts can be modified like so:

1
@Injectable()
2
export class CounterEffects {
3
constructor(
4
private store: Store,
5
private actions$: Actions,
6
) {}
7
8
readonly multiplyBy = createEffect(() =>
9
this.actions$.pipe(
10
// using multiplyBy.trigger
11
ofType(CounterActions.multiplyBy.trigger),
12
concatLatestFrom(() => this.store.select(CounterSelectors.selectValue)),
13
// switchMap to a mock side-effect (timer)
14
switchMap(([{ multiplier }, currentValue]) =>
15
// delay 1s to simulate async task
16
timer(1000).pipe(
17
// return multiplyBy.success action
18
map(() =>
19
CounterActions.multiplyBy.success({
20
value: currentValue * multiplier,
21
}),
22
),
23
),
24
),
25
),
26
);
27
}

You can see that for simple features like a Counter, all the logic is handled in a single counter.slice.ts, and every building block is generated thanks to TypeScript.

Miscellaneous

Of course, there will be cases where more complex features do not benefit as much from ngrx-slice but it does not mean you cannot use ngrx-slice for those. The returned selectors and actions are just abstractions using createSelector and createAction under the hood. Hence, you can use/compose those like normal NgRx Selectors.

Entity is something tricky when used with ngrx-slice. Supposedly, ngrx/entity helps with providing utilities to immutably update list data. With ngrx-slice, you can update your list/array mutably with Immer. For example:

ngrx/entity
1
// adding a new item to a list
2
// immutable way
3
[...state.items, newItem];
4
entity.addOne(newItem, state);
5
// ngrx-slice
6
state.items.push(newItem);

That is all. Go ahead and give ngrx-slice a try. Feel free to reach out to me on Twitter @Nartc1410 if you have any questions or just want to chat, I’d love to hear from you. If you run into any issues, please feel free to open an issue on ngrx-slice Github. Thank you for reading.

Special Mentions

Published on Tue Aug 10 2021


Angular NgRx