Why is OnInitializedAsync() called twice on a page reload

David Thielen 2,231 Reputation points
2024-03-17T23:34:40.2933333+00:00

Hi all;

Normally when a page is being created & rendered in Blazor version 8, RenderMode.InteractiveServer, OnInitializedAsync() is called once. But when I do a Reload on Chrome, it is called twice. And all child components in the page are called twice too.

Why is it being called twice? And what can I do to avoid reading from the database to populate the page twice? And very importantly, in a way that will call from the database at least once for any situation?

thanks - dave

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,371 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ping Ni-MSFT 2,085 Reputation points Microsoft Vendor
    2024-03-18T02:22:05.1466667+00:00

    Hi @David Thielen ,
    It is called twice, as you are using pre-rendering. Go to App.razor and globally set the render mode like below:

    <Routes @rendermode="new InteractiveServerRenderMode(prerender:false)" />
    

    Using a cache to temporarily store database query results can be a useful strategy to prevent having to query the database multiple times in quick succession. It reduces the load on the database but initial visit might still be a little slower.
    For your second option, very fast initial render because no heavy operations are performed in OnInitializedAsync() but the user might see a flash of loading content or incomplete content, which can be perceived as jarring.
    A third approach is that you can perform fast operations in OnInitializedAsync() to ensure a rapid render (such as loading cached data or defaults), and then perform the slower database query in the background. Once the data is available, the component state can be updated, which will automatically trigger a rerender.
    For example, you could initiate a background task to fetch the data and then call StateHasChanged() on its completion to update the UI accordingly. To avoid this background task in the pre-rendering phase, you can check the IComponentContext.IsConnected property in Blazor Server applications to determine if the component is being interactively used by a client. No matter which approach to use will depend on your specific application requirements.

    Reference:

    Stateful reconnection after prerendering
    Persist prerendered state


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena


0 additional answers

Sort by: Most helpful