[Solved] Why is my blazor component loading twice

Admin | Last updated 09/01/2024

This happens because of Pre-rendering of blazor components

This is default behavior in

  • Blazor Web App (Interactive Server, Interactive WebAssembly, and InteractiveAuto) - .Net 8
How this works is,

Blazor pre-renders the component on the server, i.e. calls OnInitialized (OnInitializedAsync) method on the server,

generates the HTML for the component,

returns the generated HTML to the browser

After this

On the client side (in browser), Blazor Initialize the component again for the interactivity, thus calls the OnInitialized (OnInitializedAsync) method again

Solution(s):  

  1. Disable the pre-rendering for the component

  2. Handle the data fetching in OnInitialized using PersistentComponentState, which allows you to fetch the data in pre-rendering, and then passing the data to the client in serialized form, and then use this data on the client (without re-fetching from the server/database)

You can follow this youtube video for in-depth explanation and solution 
How to Fix the Issue with Blazor Prerendering - OnInitialized Gets Called Twice

Comments

No comments yet. Be the first to leave a comment

Add a New Comment
An unhandled error has occurred. Reload 🗙