If your Blazor application calls the OnInitializedAsync() method multiple times, there can be a simple reason. Before discussing the solution, first, let’s understand when the OnInitializedAsync() method executes twice.
When you run the Blazor application, it prerenders on the initial page as a static HTML on the first page request. During this prerendering, it calls all lifecycle methods like OnInitializedAsync() and OnParametersSetAsync() methods of Blazor components. At this time, your OnInitializedAsync() executes the first time. After this, Blazor transitions to interactive mode and re-renders your components, where lifecycle methods will again get called, and your OnInitializedAsync() method will be called a second time.
To avoid calling OnInitializedAsync() method twice, change Blazor render mode from ServerPrerendered to Server. To change the RenderMode, go to _host.cshtml in the Pages folder and change render-mode for App and Headoutlet components as shown below.
@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace BlazorApp1.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<link href="BlazorApp1.styles.css" rel="stylesheet" />
<link rel="icon" type="image/png" href="favicon.png"/>
<component type="typeof(HeadOutlet)" render-mode="Server" />
</head>
<body>
<component type="typeof(App)" render-mode="Server" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
Unlike RenderMode. ServerPrerendered, RenderMode.Server will not execute any components during initial page load and executes code inside the component only during interactive rendering. So, the OnInitializedAsync() method gets called only once during interactive rendering.
Suppose you don’t want to change render mode from ServerPrerendered to Server. In that case, you have to write your own code to avoid code inside the OnInitializedAsync() method executing a second time, like having a flag identifying whether the call is the first or the second time.