Understanding InjectionContext and Signal Effects
Published: 2024-01-08 15:54:48

---
title: Understanding InjectionContext and Signal Effects
published: true
date: 2023-10-12 18:48:45 UTC
tags: 
canonical_url: https://www.danywalls.com/understanding-injectioncontext-and-signal-effects
---

Yesterday, I was chatting with my friend [Jrgen de Groot](https://hashnode.com/@Alt148) about Signals. As our conversation shifted to cover effects, he encountered the error ERROR NG0203.

Later, another friend approached me with the same issue. I decided to compose a brief article to explain why it happens.

## Scenario

We have a counter app using signals to update the times of clicks, when the count signals variable gets 10, we must update a local variable (no signals) to 'You reached the limit of clicks'.

## Using Effect

The signal effect is very useful for handling side effects. In our case, we have a side effect where the variable 'limitMessage' needs to be updated when the 'counts' variable reaches 10.

```
@Component({ selector: 'my-app', standalone: true, imports: [CommonModule, FormsModule], template: ` <h1>{{limitMessage}}</h1> <h2>{{ count()}} times</h2> <button (click)="increase()">+1</button> `,})export class App { count = signal(0); limitMessage = 'Feel free to click!'; increase() { this.count.update((p) => p + 1); }}bootstrapApplication(App);
```

We run the effect in the `ngOnInit` lifecycle to track the changes in the `count` variables.

```
export class App implements OnInit { count = signal(0); limitMessage = 'Feel free to click!'; ngOnInit(): void { effect(() => { if (this.count() == 10) { this.limitMessage = 'You reached the limit, sorry'; } }); }
```

Darn!!!! We got the error!!

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1697102152291/068766e0-86b5-4390-b593-a8f5a20b14df.png)

## Effects and Injection Context

The effect must be used in an injection context because it uses the DestroyRef service to unsubscribe when the building block is destroyed.

### The Constructor

The first approach is to move the effect to the constructor, and save changes, yeah! the effect runs!!

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1697102840311/5771b7ff-3f33-41a8-9d76-0551d1aad4c4.png)

## Using runInjectionContext

To use the effect outside of the constructor, we must use the `runInjectionContext` function, by injecting the `Injector`.

```
export class App implements OnInit { count = signal(0); limitMessage = 'Feel free to click!'; disabled = signal(false); #injector = inject(Injector); ngOnInit(): void { runInInjectionContext(this.#injector, () => { effect(() => { if (this.count() == 10) { this.limitMessage = 'You reached the limit, sorry'; } }); }); } increase() { this.count.update((p) => p + 1); }}
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1697104012457/6510ef90-5ffa-4318-a6ee-eec49edf330b.png)

Yes! We have the effect outside of the class constructor! And no errors!

## Update Signals In Effects

We are using effects without problems, but let's add a small feature connected to my effect. I want to disable the button when the count reaches 10.

I want to create the variable '`disabled`' as a boolean signal and use the effect to update the value.

```
export class App implements OnInit { count = signal(0); limitMessage = 'Feel free to click!'; disabled = signal(false); #injector = inject(Injector); ngOnInit(): void { runInInjectionContext(this.#injector, () => { effect(() => { if (this.count() == 10) { this.limitMessage = 'You reached the limit, sorry'; this.disabled.update(() => true); } }); }); } increase() { this.count.update((p) => p + 1); }}
```

Save changes then try to update the disabled signals!!! DAMM!!!!!!!!

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1697134821770/efcda28f-13ae-49a5-9be3-25a21acc38ac.png)

By default, effects aren't allowed to update signals, but for these scenarios, we can disable this restriction by setting `allowSignalWrite` it to true.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1697135511537/52b2d23d-c2e5-454e-8bf5-836c546afe0d.png)

Perfect! we are working with Signals effect without any problem!

## Recap

We learn how to implement the effect in the ngOnInit lifecycle, explore the importance of the injection context, how to use runInInjectionContext to avoid errors, and update Signals in effects by disabling the default restriction using the allowSignalWrite option.

I hope this helps you when you start using Signals and effects! ;)

> [Source Code](https://stackblitz.com/edit/stackblitz-starters-p27zhz?file=src%2Fmain.ts)