Hey Dorothea
Hey Dorothea

Reputation: 33

Blazor - Avoid OnInitialized/OnInitializedAsync

I made two components in Blazor that are toggled when a button is pressed, like the following:

<div class="row full-height">
   <div class="col-md-12">
      @if (condition)
      {
         <Component1 Parameter="foo"> 
         </Component1>
      }
      else
      {
         <Component2 Parameter="bar"></Component2>
      }
   </div>
</div>

When one of this components rerenders, it performs OnInitialized and OnInitializedAsync again. I was wondering if there's a way I could execute the code inside those methods only once.

Thank you very much!

Upvotes: 1

Views: 4667

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30016

Your problem is you are removing and adding the components to the RenderTree every time you toggle.

Instead use a simple Show parameter on each component. The components now only get added to the RenderTree when Index first renders.

A quick demo below:

Component 1

@if (this.Show)
{
<h3>Component1</h3>
<div>Rendered at : @rendertime</div>
}

@code {

    [Parameter] public bool Show { get; set; }

    string rendertime;

        protected override void OnInitialized()
        {
        rendertime = DateTime.Now.ToLongTimeString();
            base.OnInitialized();
        }

}

Component 2

@if (this.Show)
{
<h3>Component2</h3>
<div>Rendered at : @rendertime</div>
}

@code {

    [Parameter] public bool Show { get; set; }

    string rendertime;

        protected override void OnInitialized()
        {
        rendertime = DateTime.Now.ToLongTimeString();
            base.OnInitialized();
        }

}

index.razor

@page "/"
@using StackOverflow.Answers.Components

<Component1 Show="_show1"/>

<Component2 Show="_show2"/>

<div class="m-2 p-2">
    <button class="btn btn-dark" @onclick="ShowComponent1"> Toggle 1</button>
    <button class="btn btn-secondary ms-2" @onclick="ShowComponent2"> Toggle 2</button>
    <button class="btn btn-primary ms-2" @onclick="Toggle"> Toggle</button>
</div>

@code {

    bool _show1;
    bool _show2;

    void ShowComponent1()
    {
        _show1 = !_show1;
    }

    void ShowComponent2()
    {
        _show2 = !_show2;
    }

    void Toggle()
    {
        if (_show2)
        {
            _show2 = false;
            _show1 = true;
        }
        else
        {
            _show2 = true;
            _show1 = false;
        }
    }
}

Upvotes: 4

Related Questions