# Component Lifecycle

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Blazor Components
Source: https://www.devtutorials.ai/learn/blazor/components/component-lifecycle

> The order of Blazor's lifecycle methods: OnInitialized(Async), SetParametersAsync, OnParametersSet(Async), route parameter changes, re-render triggers, StateHasChanged, ShouldRender, @key, OnAfterRender with firstRender, and Dispose.

## Lifecycle Overview

- The component lifecycle is the set of steps a component goes through: it is created, updated and removed.
- At each step, Blazor calls a lifecycle method, for example `OnInitialized`.
- You use them by writing `protected override` and the method name in `@code`.
- Using lifecycle methods lets you load data, update values and clean up at the right time.

**Real-World Example:**

- Ravi's order page loads the menu when it opens.
- It updates the bill when the cups change.
- It stops a timer when the customer leaves.
- Each job uses a different lifecycle method.

**Simple lesson:** Lifecycle methods let you run code at the right moment in a component's life.

## Lifecycle Order

Blazor calls the methods in this order:

1. `SetParametersAsync`: the parameters arrive.
2. `OnInitialized` / `OnInitializedAsync`: **first time only**.
3. `OnParametersSet` / `OnParametersSetAsync`: every time the parameters are set.
4. **Render**: Blazor works out the HTML.
5. `OnAfterRender` / `OnAfterRenderAsync`: the HTML is now in the browser.
6. `Dispose`: the component is removed (only if you implement it).

<figure className="blz-fig">
<svg viewBox="0 0 640 250" role="img" aria-labelledby="fig-lc-order">
  <title id="fig-lc-order">Animation: a dot moves through the lifecycle steps in order: SetParametersAsync, OnInitialized (first time only), OnParametersSet, Render, OnAfterRender. A loop arrow goes from OnAfterRender back to OnParametersSet for later updates. Dispose sits at the end.</title>
  <defs><marker id="lc-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="10" y="30" width="110" height="56" rx="8" />
  <text className="t m" x="65" y="54" textAnchor="middle" style={{ fontSize: 10 }}>SetParameters</text>
  <text className="t m" x="65" y="70" textAnchor="middle" style={{ fontSize: 10 }}>Async</text>
  <rect className="pur" x="135" y="30" width="110" height="56" rx="8" />
  <text className="t m" x="190" y="54" textAnchor="middle" style={{ fontSize: 11 }}>OnInitialized</text>
  <text className="t" x="190" y="72" textAnchor="middle" style={{ fontSize: 10 }}>first time only</text>
  <rect className="blu" x="260" y="30" width="120" height="56" rx="8" />
  <text className="t m" x="320" y="62" textAnchor="middle" style={{ fontSize: 11 }}>OnParametersSet</text>
  <rect className="org" x="395" y="30" width="90" height="56" rx="8" />
  <text className="t" x="440" y="62" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Render</text>
  <rect className="grn" x="500" y="30" width="130" height="56" rx="8" />
  <text className="t m" x="565" y="62" textAnchor="middle" style={{ fontSize: 11 }}>OnAfterRender</text>
  <path className="line" d="M120 58 H131" markerEnd="url(#lc-a1)" />
  <path className="line" d="M245 58 H256" markerEnd="url(#lc-a1)" />
  <path className="line" d="M380 58 H391" markerEnd="url(#lc-a1)" />
  <path className="line" d="M485 58 H496" markerEnd="url(#lc-a1)" />
  <path className="line" d="M565 86 V130 H320 V90" markerEnd="url(#lc-a1)" style={{ strokeDasharray: "5 4" }} />
  <text className="t" x="442" y="150" textAnchor="middle" style={{ fontSize: 12 }}>parent sends new parameters: run again (no OnInitialized)</text>
  <rect className="box" x="250" y="180" width="140" height="48" rx="8" />
  <text className="t m" x="320" y="209" textAnchor="middle" style={{ fontSize: 12 }}>Dispose (removed)</text>
  <circle r="7" cy="58" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="65;190;320;440;565" dur="5s" repeatCount="indefinite" calcMode="discrete" />
  </circle>
</svg>
<figcaption>The lifecycle in order. Later updates skip OnInitialized and start again at OnParametersSet.</figcaption>
</figure>

Press **▶ Run** and read the **Console**. Each method prints its name, so you can see the order. Then click the button.

The box opens on **Bill.razor**, which has the lifecycle methods. **Order.razor** is its parent.

<button @onclick="() => cups++">Add cup</button>

@code {
      private int cups = 1;
}
`,
    "Components/Bill.razor": `<p>Bill: ₹@(Cups * 20)</p>

@code {
      [Parameter] public int Cups { get; set; }

      protected override void OnInitialized()
      {
          Console.WriteLine("1. OnInitialized (first time only)");
      }

      protected override void OnParametersSet()
      {
          Console.WriteLine($"2. OnParametersSet: Cups = {Cups}");
      }

      protected override void OnAfterRender(bool firstRender)
      {
          Console.WriteLine($"3. OnAfterRender: firstRender = {firstRender}");
      }
}
`,
  }}
/>

- On the first run you see 1, 2 and 3. After a click you see only 2 and 3. `OnInitialized` does not run again.

**Simple lesson:** Initialize once, then parameters, render and after-render, again and again. Dispose at the end.

## Initialization

### OnInitialized

- Runs **once**, when the component is first created.
- Parameters are already set, so you can use them here.
- Use it to set starting values.

### OnInitializedAsync

- The **async** version. Use it when you must wait for something, like loading data from a web API.
- Blazor renders the page **before** the wait ends, and again **after** it. So show a "Loading..." message while the data is `null`.

@if (menu == null)
{
      <p>Loading...</p>
}
else
{
      <ul>
          @foreach (var tea in menu)
          {
              <li>@tea</li>
          }
      </ul>
}

@code {
      private string[]? menu;

      protected override async Task OnInitializedAsync()
      {
          await Task.Delay(1000); // pretend to call a web API
          menu = new[] { "Masala Tea", "Ginger Tea", "Lemon Tea" };
      }
}
`,
  }}
/>

Always handle `null` while async data loads. If you write `@foreach (var tea in menu)` without the `@if`, the first render fails, because `menu` is still `null`.

**Simple lesson:** Use `OnInitialized` for starting values, and `OnInitializedAsync` to load data. Show "Loading..." until it arrives.

## Parameter Updates

### SetParametersAsync

- The very first step. It receives **all** incoming parameters and copies them into your properties.
- You rarely override it. If you do, call `await base.SetParametersAsync(parameters)`. Otherwise your properties stay empty.

In the below example, `TeaCup.razor` overrides `SetParametersAsync`. It saves the old `Size`, calls `base.SetParametersAsync` to copy in the new value, and then shows both.

<button @onclick='() => size = "Large"'>Large</button>

@code {
      private string size = "Small";
}
`,
    "Components/Pages/TeaCup.razor": `<p>Cup size: @Size</p>

@foreach (var line in log)
{
      <p>@line</p>
}

@code {
      [Parameter] public string Size { get; set; } = "";

      private List<string> log = new();

      public override async Task SetParametersAsync(ParameterView parameters)
      {
          string before = Size;

          // Copies the new values into the [Parameter] properties
          await base.SetParametersAsync(parameters);

          log.Add($"SetParametersAsync: '{before}' → '{Size}'");
      }
}
`,
  }}
/>

- Click **Large**. A new line shows the old and the new size. Without the `base.SetParametersAsync` line, `Size` is never set and the cup does not update.

### OnParametersSet

- Runs after the parameters are set: on the first render **and** every time the parent sends new values.
- Use it to work out values that depend on parameters, like a total.

### OnParametersSetAsync

- The async version, for example to load data for a new parameter value.

### Route Parameter Changes

- When a user goes from `/tea/masala` to `/tea/ginger`, Blazor **reuses** the same page component. It does not create a new one.
- So `OnInitialized` does **not** run again. Only `OnParametersSet` runs.
- Load data that depends on a route parameter in `OnParametersSet(Async)`, not in `OnInitialized`.

<figure className="blz-fig">
<svg viewBox="0 0 640 180" role="img" aria-labelledby="fig-lc-ops">
  <title id="fig-lc-ops">Animation: the parent Home sends Name = masala, then Name = ginger, to TeaDetails. Each time a value arrives, OnParametersSet runs and the price updates from 20 to 25.</title>
  <defs><marker id="fig-lc-ops-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="50" width="150" height="80" rx="8" />
  <text className="t m" x="95" y="80" textAnchor="middle" style={{ fontSize: 13 }}>Home (parent)</text>
  <text className="t" x="95" y="105" textAnchor="middle" style={{ fontSize: 11 }}>sends Name</text>
  <path className="line" d="M170 90 H300" markerEnd="url(#fig-lc-ops-a)" />
  <text className="t m" x="235" y="80" textAnchor="middle" style={{ fontSize: 12 }}>Name = "masala"<animate attributeName="opacity" values="1;0;1" keyTimes="0;0.5;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t m" x="235" y="80" textAnchor="middle" style={{ fontSize: 12 }} opacity="0">Name = "ginger"<animate attributeName="opacity" values="0;1;0" keyTimes="0;0.5;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <circle r="6" cy="90" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="175;295;295;175;295;295" keyTimes="0;0.2;0.5;0.5;0.7;1" dur="6s" repeatCount="indefinite" />
  </circle>
  <rect className="blu" x="305" y="30" width="315" height="120" rx="8" />
  <text className="t m" x="462" y="58" textAnchor="middle" style={{ fontSize: 13 }}>TeaDetails</text>
  <rect className="org" x="335" y="72" width="255" height="30" rx="6" />
  <text className="t m" x="462" y="92" textAnchor="middle" style={{ fontSize: 12 }}>OnParametersSet() runs</text>
  <text className="t" x="462" y="132" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Price: ₹20<animate attributeName="opacity" values="1;0;1" keyTimes="0;0.7;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t" x="462" y="132" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }} opacity="0">Price: ₹25<animate attributeName="opacity" values="0;1;0" keyTimes="0;0.7;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
</svg>
<figcaption>Every new parameter value runs OnParametersSet again, so the price stays correct.</figcaption>
</figure>

This is a common bug: the address changes to `/tea/ginger`, but the page still shows Masala data. The fix is to move the loading code from `OnInitialized` to `OnParametersSet`.

In the box below, `Home` changes the `Name` parameter, like a user moving between tea pages.

The box opens on **TeaDetails.razor**. Compare the code in `OnInitialized` and `OnParametersSet`.

<button @onclick='() => tea = "ginger"'>Ginger</button>

@* Like the Router going from /tea/masala to /tea/ginger *@

@code {
      private string tea = "masala";
}
`,
    "Components/Pages/TeaDetails.razor": `@page "/tea/{Name}"

<p>Showing: @Name</p>
<p>Price from OnInitialized: ₹@priceAtStart</p>
<p>Price from OnParametersSet: ₹@price</p>

@code {
      [Parameter] public string Name { get; set; } = "";

      private int priceAtStart;
      private int price;

      protected override void OnInitialized()
      {
          priceAtStart = GetPrice(Name); // runs only once
      }

      protected override void OnParametersSet()
      {
          price = GetPrice(Name); // runs on every change
      }

      private int GetPrice(string tea) => tea == "ginger" ? 25 : 20;
}
`,
  }}
/>

- Click **Ginger**. The `OnParametersSet` price changes to ₹25. The `OnInitialized` price stays at ₹20, because it ran only once.

**Simple lesson:** Values that depend on parameters belong in `OnParametersSet`, because it runs on every change.

## Rendering

### Re-rendering Triggers

Blazor renders a component again automatically when:

- An event handler in it finishes, like `@onclick`.
- Its parent renders and passes it parameters.
- An `EventCallback` it raised finishes (the parent renders).
- You call `StateHasChanged()`.

<figure className="blz-fig">
<svg viewBox="0 0 640 210" role="img" aria-labelledby="fig-lc-rerender">
  <title id="fig-lc-rerender">Animation: four triggers send a dot, one after another, into the Render step: an event handler like @onclick finishing, the parent passing parameters, an EventCallback finishing, and a call to StateHasChanged. After Render, the page updates.</title>
  <defs><marker id="fig-lc-rerender-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="10" y="10" width="200" height="40" rx="8" />
  <text className="t m" x="110" y="35" textAnchor="middle" style={{ fontSize: 12 }}>@onclick finishes</text>
  <rect className="box" x="10" y="60" width="200" height="40" rx="8" />
  <text className="t m" x="110" y="85" textAnchor="middle" style={{ fontSize: 12 }}>parent passes parameters</text>
  <rect className="box" x="10" y="110" width="200" height="40" rx="8" />
  <text className="t m" x="110" y="135" textAnchor="middle" style={{ fontSize: 12 }}>EventCallback finishes</text>
  <rect className="box" x="10" y="160" width="200" height="40" rx="8" />
  <text className="t m" x="110" y="185" textAnchor="middle" style={{ fontSize: 12 }}>StateHasChanged()</text>
  <path className="line" d="M210 30 C280 30 280 105 345 105" markerEnd="url(#fig-lc-rerender-a)" />
  <path className="line" d="M210 80 C280 80 280 105 345 105" markerEnd="url(#fig-lc-rerender-a)" />
  <path className="line" d="M210 130 C280 130 280 105 345 105" markerEnd="url(#fig-lc-rerender-a)" />
  <path className="line" d="M210 180 C280 180 280 105 345 105" markerEnd="url(#fig-lc-rerender-a)" />
  <rect className="org" x="350" y="80" width="110" height="50" rx="8" />
  <text className="t" x="405" y="110" textAnchor="middle" style={{ fontSize: 14, fontWeight: 700 }}>Render</text>
  <path className="line" d="M460 105 H495" markerEnd="url(#fig-lc-rerender-a)" />
  <rect className="grn" x="500" y="80" width="130" height="50" rx="8" />
  <text className="t m" x="565" y="110" textAnchor="middle" style={{ fontSize: 12 }}>page updated</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="210;345;565;210;345;565;210;345;565;210;345;565" keyTimes="0;0.15;0.25;0.25;0.4;0.5;0.5;0.65;0.75;0.75;0.9;1" dur="8s" repeatCount="indefinite" calcMode="linear" />
    <animate attributeName="cy" values="30;105;105;80;105;105;130;105;105;180;105;105" keyTimes="0;0.15;0.25;0.25;0.4;0.5;0.5;0.65;0.75;0.75;0.9;1" dur="8s" repeatCount="indefinite" calcMode="linear" />
  </circle>
</svg>
<figcaption>Any of these four things makes Blazor render the component again.</figcaption>
</figure>

### Manual Updates (StateHasChanged)

- Some changes happen **outside** a Blazor event, for example a timer.
- Blazor does not know about them, so the page does not update.
- Call `StateHasChanged()` to say "my data changed, please render again".
- From a timer, use `InvokeAsync(StateHasChanged)`.

<p>Seconds: @seconds</p>

@code {
      private int seconds = 0;
      private System.Threading.Timer? timer;

      protected override void OnInitialized()
      {
          timer = new System.Threading.Timer(_ =>
          {
              seconds++;
              InvokeAsync(StateHasChanged); // the timer is not a Blazor event
          }, null, 1000, 1000);
      }

      public void Dispose()
      {
          timer?.Dispose(); // stop the timer when the page closes
      }
}
`,
  }}
/>

- Delete the line with `InvokeAsync(StateHasChanged)` and press **▶ Run**. The number stays at 0, even though `seconds` keeps growing.

### Render Control (ShouldRender)

- `ShouldRender()` returns `true` or `false`. If it returns `false`, Blazor skips the update.
- Use it rarely, only to skip costly renders. The first render always happens.

<button @onclick="() => orders++">New order</button>
<button @onclick="() => paused = !paused">@(paused ? "Resume" : "Pause") screen</button>

@code {
      private int orders = 0;
      private bool paused = false;

      protected override bool ShouldRender()
      {
          return !paused;
      }
}
`,
  }}
/>

- Click **Pause screen**, then **New order** a few times. The number does not change. Click **Resume**, and the real count appears.
- Notice the pause button's own text also stays the same while paused. Nothing in this component renders.

### Element Keys (@key)

- When a list changes, Blazor matches old and new items **by position**.
- If you add an item at the top, every row is matched with the wrong item. Text typed in a box can jump to the wrong row.
- `@key` gives each row a fixed ID, so Blazor matches items **by key** instead.

<figure className="blz-fig">
<svg viewBox="0 0 620 210" role="img" aria-labelledby="fig-lc-key">
  <title id="fig-lc-key">Animation: a new tea, Lemon, is added at the top of a list. Without @key, the note typed next to Masala moves to Lemon's row. With @key, the note stays with Masala.</title>
  <text className="t" x="150" y="22" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Without @key</text>
  <text className="t" x="470" y="22" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>With @key</text>
  <line x1="310" y1="10" x2="310" y2="200" style={{ stroke: "var(--line)" }} />
  <g>
    <rect className="box" x="40" y="40" width="220" height="32" rx="6" />
    <text className="t m" x="52" y="61" style={{ fontSize: 12 }}>
      <tspan>Masala<animate attributeName="opacity" values="1;0;0" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" /></tspan>
    </text>
    <text className="t m" x="52" y="61" style={{ fontSize: 12 }} opacity="0">Lemon (new)<animate attributeName="opacity" values="0;1;1" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" /></text>
    <rect className="org" x="170" y="45" width="80" height="22" rx="4" />
    <text className="t m" x="210" y="61" textAnchor="middle" style={{ fontSize: 11 }}>"no sugar"</text>
    <rect className="box" x="40" y="80" width="220" height="32" rx="6" opacity="0"><animate attributeName="opacity" values="0;1;1" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" /></rect>
    <text className="t m" x="52" y="101" style={{ fontSize: 12 }} opacity="0">Masala<animate attributeName="opacity" values="0;1;1" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" /></text>
    <text className="t" x="150" y="150" textAnchor="middle" style={{ fontSize: 12, fill: "#dc2626" }}>✗ the note moved to Lemon</text>
  </g>
  <g>
    <rect className="box" x="360" y="40" width="220" height="32" rx="6" opacity="0"><animate attributeName="opacity" values="0;1;1" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" /></rect>
    <text className="t m" x="372" y="61" style={{ fontSize: 12 }} opacity="0">Lemon (new)<animate attributeName="opacity" values="0;1;1" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" /></text>
    <g>
      <animateTransform attributeName="transform" type="translate" values="0,0;0,40;0,40" keyTimes="0;0.5;1" dur="4s" repeatCount="indefinite" calcMode="discrete" />
      <rect className="box" x="360" y="40" width="220" height="32" rx="6" />
      <text className="t m" x="372" y="61" style={{ fontSize: 12 }}>Masala</text>
      <rect className="grn" x="490" y="45" width="80" height="22" rx="4" />
      <text className="t m" x="530" y="61" textAnchor="middle" style={{ fontSize: 11 }}>"no sugar"</text>
    </g>
    <text className="t" x="470" y="150" textAnchor="middle" style={{ fontSize: 12, fill: "#16a34a" }}>✓ the note stays with Masala</text>
  </g>
</svg>
<figcaption>@key tells Blazor which row is which, so the right data stays with the right item.</figcaption>
</figure>

<h4>Without @@key</h4>
@foreach (var tea in teas)
{
      <p>@tea <input placeholder="note" /></p>
}

<h4>With @@key</h4>
@foreach (var tea in teas)
{
      <p @key="tea">@tea <input placeholder="note" /></p>
}

@code {
      private List<string> teas = new() { "Masala Tea", "Ginger Tea" };

      private void AddToTop()
      {
          teas.Insert(0, "Lemon Tea");
      }
}
`,
  }}
/>

- Type a note next to **Masala Tea** in both lists, then click the button. Without `@key`, your note jumps to **Lemon Tea**. With `@key`, it stays with **Masala Tea**.

**Simple lesson:** Blazor re-renders after events and parameter changes. Call `StateHasChanged` for other changes. Use `@key` in lists that change.

## After Render

### OnAfterRender

- Runs after the HTML is in the browser.
- Use it for work that needs the real page, like calling a JavaScript library to draw a chart.

### OnAfterRenderAsync

- The async version, for example to call JavaScript and wait for it.

### First Render (firstRender)

- Both methods get `bool firstRender`. It is `true` only the first time.
- Put one-time setup inside `if (firstRender) { ... }`. Otherwise it runs after **every** render.
- If you change data here, call `StateHasChanged()`. Blazor does not render again on its own after this method.

<p>Renders so far: @renders</p>
<button @onclick="() => { }">Render again</button>

@code {
      private string status = "Starting...";
      private int renders = 0;

      protected override void OnAfterRender(bool firstRender)
      {
          renders++;
          Console.WriteLine($"OnAfterRender, firstRender = {firstRender}");

          if (firstRender)
          {
              status = "Ready!";
              StateHasChanged(); // show the new status
          }
      }
}
`,
  }}
/>

- **Renders so far** is always one behind. It changes **after** the HTML is drawn, so the next render shows it.

Never call `StateHasChanged()` in `OnAfterRender` **without** `if (firstRender)`. Each render would start a new render, forever.

**Simple lesson:** `OnAfterRender` runs after the HTML is in the browser. Do one-time setup only when `firstRender` is `true`.

## Disposal

- Disposal means cleaning up or releasing resources when a component is no longer needed.
- It helps stop running tasks, remove event subscriptions, and free resources to avoid unnecessary memory usage.

<figure className="blz-fig">
<svg viewBox="0 0 640 170" role="img" aria-labelledby="fig-lc-dispose">
  <title id="fig-lc-dispose">Animation: a TeaTimer component is on the page with its timer ticking. The user goes to another page. Blazor calls Dispose, the timer stops, and the component is removed.</title>
  <defs><marker id="fig-lc-dispose-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="40" width="200" height="110" rx="8">
    <animate attributeName="opacity" values="1;1;0.25;0.25" keyTimes="0;0.6;0.75;1" dur="6s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="120" y="70" textAnchor="middle" style={{ fontSize: 13 }}>TeaTimer</text>
  <text className="t" x="120" y="100" textAnchor="middle" style={{ fontSize: 12 }}>⏱ timer: ticking<animate attributeName="opacity" values="1;0;0" keyTimes="0;0.7;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t" x="120" y="100" textAnchor="middle" style={{ fontSize: 12 }} opacity="0">⏹ timer: stopped<animate attributeName="opacity" values="0;1;1" keyTimes="0;0.7;1" dur="6s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t" x="120" y="130" textAnchor="middle" style={{ fontSize: 11 }}>on the page</text>
  <rect className="box" x="250" y="10" width="140" height="40" rx="8" />
  <text className="t m" x="320" y="35" textAnchor="middle" style={{ fontSize: 12 }}>user goes to /menu</text>
  <path className="line" d="M320 50 V75" markerEnd="url(#fig-lc-dispose-a)" />
  <rect className="org" x="260" y="80" width="120" height="44" rx="8">
    <animate attributeName="opacity" values="0.3;0.3;1;1" keyTimes="0;0.45;0.55;1" dur="6s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="320" y="107" textAnchor="middle" style={{ fontSize: 12 }}>Dispose()</text>
  <path className="line" d="M380 102 H445" markerEnd="url(#fig-lc-dispose-a)" />
  <rect className="grn" x="450" y="60" width="170" height="84" rx="8" />
  <text className="t m" x="535" y="92" textAnchor="middle" style={{ fontSize: 12 }}>timer stopped</text>
  <text className="t m" x="535" y="118" textAnchor="middle" style={{ fontSize: 12 }}>memory freed</text>
  <circle r="7" cy="102" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="225;225;320;535;535" keyTimes="0;0.4;0.55;0.7;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>When the component leaves the page, Blazor calls Dispose so the timer stops.</figcaption>
</figure>

### @implements

- `@implements` tells the component to follow a specific interface, such as `IDisposable`.
- It is the Razor equivalent of writing `: IDisposable` in a C# class.

### IDisposable

- Use `IDisposable` when the component starts something that needs to be stopped later, such as a timer or event subscription.
- Add `@implements IDisposable` and create a `Dispose()` method.
- Blazor automatically calls `Dispose()` when the component is removed from the page, such as when navigating to another page.

In the below example, `TeaTimer.razor` starts a timer, and its `Dispose()` method stops the timer when the component is removed.

      @(showTimer ? "Close" : "Open") the tea timer
</button>

@if (showTimer)
{
}

@code {
      private bool showTimer = true;
}
`,
    "Components/TeaTimer.razor": `@implements IDisposable

<p>⏱ Tea timer: @seconds s</p>

@code {
      private int seconds = 0;
      private System.Threading.Timer? timer;

      protected override void OnInitialized()
      {
          Console.WriteLine("Timer started");
          timer = new System.Threading.Timer(_ =>
          {
              seconds++;
              InvokeAsync(StateHasChanged);
          }, null, 1000, 1000);
      }

      public void Dispose()
      {
          timer?.Dispose();
          Console.WriteLine("Dispose: timer stopped");
      }
}
`,
  }}
/>

- Click **Close the tea timer**. The `@if` removes `TeaTimer`, so Blazor calls `Dispose`. The **Console** shows "Dispose: timer stopped".

### IAsyncDisposable

- Use `IAsyncDisposable` when cleanup requires an asynchronous operation, such as releasing a JavaScript object.
- Add `@implements IAsyncDisposable` and create a `DisposeAsync()` method.

**Simple lesson:** Stop timers and subscriptions in `Dispose`. Add `@implements IDisposable` to get it called.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Loading route data in `OnInitialized` | It runs on every page change | Use `OnParametersSet(Async)` | The page keeps the old data |
| `@foreach` over data that is still loading | The data is there at the first render | Check for `null` first and show "Loading..." | An error on the first render |
| Changing data in a timer without `StateHasChanged` | Blazor sees every change | Call `InvokeAsync(StateHasChanged)` | The page does not update |
| `StateHasChanged()` in `OnAfterRender` without `firstRender` | It runs once | Wrap it in `if (firstRender)` | Renders forever |
| A list that changes, without `@key` | Blazor matches items by value | Add `@key` to each item | Typed text jumps to another row |
| A timer without `Dispose` | It stops when the page closes | `@implements IDisposable` and stop it | The timer keeps running |

</div>

## Check Yourself

## Exercises

## What to Remember

- Order: `SetParametersAsync` → `OnInitialized(Async)` (once) → `OnParametersSet(Async)` → render → `OnAfterRender(Async)` → `Dispose`.
- Load data in `OnInitializedAsync`. Handle `null` while it loads.
- Work that depends on parameters, including route parameters, goes in `OnParametersSet(Async)`.
- Call `StateHasChanged()` for changes outside Blazor events, like timers. `ShouldRender` can skip renders.
- Use `@key` in lists that change.
- Use `if (firstRender)` in `OnAfterRender`.
- Stop timers in `Dispose` with `@implements IDisposable`.

Next: **Layouts**
