---
title: "Run setup and cleanup when a C# UI component mounts and unmounts"
url: https://recursiveai.org/oneui/cookbook/subscribe-and-unsubscribe-in-component-lifecycle/
description: "Subscribe in OnMounted and unsubscribe in OnDisposed. Run a OneUI component that receives a C# event while mounted and stops receiving it when removed."
version: "1.1.0"
---

# Run setup and cleanup when a C# UI component mounts and unmounts

**OneUI** is a free, open-source .NET library from Recursive AI for writing UI components in HTML, CSS, and C# that run in native windows on desktops and phones, or in a browser via WebAssembly, with OneApp. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneUI) · [GitHub](https://github.com/recursive-ai-oss/oneui-csharp) · [Docs](https://recursiveai.org/oneui/docs/) · [Download example (.zip)](https://recursiveai.org/oneui/cookbook/subscribe-and-unsubscribe-in-component-lifecycle/subscribe-and-unsubscribe-in-component-lifecycle.zip)

Subscribe in `OnMounted`. Unsubscribe in `OnDisposed`, which runs when the component is unmounted, for example by `ui.Unmount(panel)`.

```shell
dotnet add package RecursiveAI.OneUI
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
protected override void OnMounted()
    => feed.Changed += ShowStatus;

protected override void OnDisposed()
    => feed.Changed -= ShowStatus;
```

[The example](https://recursiveai.org/oneui/cookbook/subscribe-and-unsubscribe-in-component-lifecycle/subscribe-and-unsubscribe-in-component-lifecycle.zip) is the full program below: unzip it and `dotnet run`.

These overrides go in `StatusPanel.cs`, where `feed` and `ShowStatus` are defined. The panel displays `Ready` while mounted and ignores `Offline` after removal.

## The full program

OneUI’s source generator pairs the `.html` file with the partial class of the same name and supplies the `Component` base class that defines `OnMounted` and `OnDisposed`. The example uses this package reference:

```xml
<PackageReference
    Include="RecursiveAI.OneUI"
    Version="1.1.0" />
```

`StatusPanel.html`:

```html
<p>{Status}</p>
```

`StatusPanel.cs`:

```csharp
using OneUI.Components;

public partial class StatusPanel
{
    private readonly StatusFeed feed;

    [State]
    public partial string Status { get; set; }

    public StatusPanel(StatusFeed feed)
    {
        this.feed = feed;
        Status = "Waiting";
    }

    protected override void OnMounted()
        => feed.Changed += ShowStatus;

    protected override void OnDisposed()
        => feed.Changed -= ShowStatus;

    void ShowStatus(string text)
    {
        Status = text;
        Console.WriteLine($"Received: {text}");
    }
}
```

`Demo.cs` creates the publisher, `StatusFeed`, and mounts the panel in an in-memory `ReferenceDocument`. The same publisher sends another event after the panel is removed.

```csharp
using OneUI.Components;
using OneUI.Components.Reference;

var doc = new ReferenceDocument();
var ui = new UiContext(doc);
var feed = new StatusFeed();
var panel = ui.Mount(new StatusPanel(feed));

Console.WriteLine($"Mounted: {doc.ToHtml()}");
feed.Publish("Ready");
Console.WriteLine($"Updated: {doc.ToHtml()}");

ui.Unmount(panel);
Console.WriteLine(
    "Publishing after unmount: Offline");
feed.Publish("Offline");
Console.WriteLine(
    $"Last received: {panel.Status}");

public sealed class StatusFeed
{
    public event Action<string>? Changed;

    public void Publish(string text)
        => Changed?.Invoke(text);
}
```

`dotnet run` prints:

```text
Mounted: <p>Waiting</p>
Received: Ready
Updated: <p>Ready</p>
Publishing after unmount: Offline
Last received: Ready
```

If you leave out `-=`, the external publisher still calls `ShowStatus` after unmounting the panel.

## Variations

To use a lambda for the handler, store the delegate so both callbacks use the same instance. In `StatusPanel.cs`, add the field, assign it in the constructor, and replace the two overrides:

```csharp
private readonly Action<string> handler;

// In the constructor:
handler = text => ShowStatus(text);

// In the class:
protected override void OnMounted()
    => feed.Changed += handler;

protected override void OnDisposed()
    => feed.Changed -= handler;
```

## Related recipes

- [Conditionally render HTML in a C# component template](https://recursiveai.org/oneui/cookbook/render-conditional-content-in-template/)
- [Focus an input after a C# component updates](https://recursiveai.org/oneui/cookbook/focus-input-after-component-update/)

## The short answer

Override `OnMounted` to attach the event handler with `+=`. Override `OnDisposed` to detach it with `-=` on the same publisher. That ties the subscription to the component’s time in the document, not to the lifetime of the object that publishes the event.

## When do setup and cleanup run in a UI component?

In OneUI, `OnMounted` runs after the commit that creates the component’s nodes. If a parent and child mount together, the child’s callback runs first. On removal, the parent’s `OnDisposed` runs before the child’s. Neither callback is an update hook: changing a state property on an already mounted component does not attach another handler. Removing a child by closing its conditional branch is a lifecycle change; changing the child’s display text is not. See the [markup lifecycle rules](https://recursiveai.org/oneui/docs/markup/#template-syntax).

Use the constructor to store the publisher and initialize state. Put subscription setup in `OnMounted` if events should only reach the component while it is present. The example publishes synchronously from the same thread as the UI; it does not use a background event source.

## How do you unsubscribe from a C# event when a component unmounts?

Use the same named method with `+=` and `-=`. A publisher that outlives the component can otherwise keep its callback alive and still deliver events. A long-lived application feed, for example, doesn’t know that a panel that listened to it has been removed. The sample deliberately keeps the feed alive after calling `ui.Unmount(panel)` so you can see that the callback no longer runs.

## Can you unsubscribe from an anonymous event handler in C#?

Yes, if you save the delegate when you subscribe. Rewriting the same lambda expression in the cleanup method is not a reliable way to remove the original subscription. Use a named method when you don’t need to capture anything, or store a delegate as in the variation. See [Microsoft’s C# event subscription guide](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-subscribe-to-and-unsubscribe-from-events).
