Search code examples
angulartypescriptngrx

does an ngrx effect dispatching cause a memory leak?


So I am learning NgRx and there's something that I need to wrap around my head. When I create an Effect and when an action is dispatched, the createEffect function will run. Now, from what I learned is that in the createEffect configuration is that there's a dispatch config that takes a boolean. I quote the dispatch config from the NgRx docs:

Determines if the action emitted by the effect is dispatched to the store.If false, effect does not need to return type Observable<Action>.

Suppose the dispatch is set to true (default). That means it emits an action, and since an action is emitted, createEffect() will be called, resulting in another action to be emitted. Since again, dispatch is true, the same infinite recursive cycle will repeat again.

My Reproducible example:

Example Action:

export const incrementByN = createAction('[Counter Component] Increment With N', props<{value: number}>())

Example Reducer:

export let counterReducer = (state = initialState, action: CounterActions | Action): number => {
    if (action.type === '[Counter Component] Increment') {
        return state + (action as CounterActions).value
    }
 
    return state
}

Example Effect:

@Injectable()
export class CoutnerEffect {
    saveCount = createEffect(() => {
        return this.actions$.pipe(
            ofType(incrementByN, decrement), 
            tap(action => {
                console.log(action)
            })
        )
    })
    constructor(private actions$: Actions) {}
}

Keep in mind, I think I am getting a memory leak when I set dispatch to true (the default).


Solution

  • An effect is used to handle the side effects of an application, for example to make a backend request.

    A typical effect listens to an action, handles a side effects, and dispatches a new action based on the result of the side effect. For example, it will dispatch an action containing the results of a backend request or an error action with the error.

    If you don't map the action to a new action (as within the example), the effect will continually be reinvoked because it receives the same action. This can be desired behavior in some cases for example to poll data.

    If you don't want this behavior either map the incoming action into a different action, or use the dispatch: false configuration to disable that the action will be dispatched at the end of the effect.