Recently, I started delving into ngrx and decided to educate myself by going through the official documentation on their website ngrx.io. During this exploration, I came across a puzzling piece of code in one of their reducers.
The file in question is counter.actions.ts:
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');
Now, let's take a look at the content of counter.reducer.ts:
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
const _counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, (state) => 0)
);
export function counterReducer(state, action) {
return _counterReducer(state, action);
}
Lastly, we have the app module file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, StoreModule.forRoot({ count: counterReducer })],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
After reviewing these files, some questions cropped up in my mind:
- What exactly does the following snippet do?
export function counterReducer(state, action) {
return _counterReducer(state, action);
}
present in the reducer file?
Is having counterReducer crucial?
Why not solely export _counterReducer and include it in the storeModule.forRoot within the app module file?
Interestingly, during my research on actions in ngrx, I stumbled upon this explanation:
The exported reducer function is essential due to function call limitations with the View Engine AOT compiler. However, if you opt for the default Ivy AOT compiler (or JIT), it is no longer mandatory.
Could this serve as a plausible rationale?