When should you use OnAfterRender instead of OnInitialized, and why is it the only safe place to perform JavaScript interop?
Last updated
OnInitializedruns before rendering, whileOnAfterRenderruns once the DOM exists, so use it for JS interop, focusing elements, and initializing JS widgets.Interop is only safe there because during prerendering there is no live JS runtime or circuit yet, so
IJSRuntimecalls fail earlier.Guard one-time setup with
if (firstRender)and avoid carelessStateHasChangedcalls here (they can cause render loops).
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-10.0
- https://wiemksaier.medium.com/the-hidden-magic-behind-rendering-in-blazor-0e50c127f454
- https://medium.com/@shreyans_padmani/understanding-blazor-compontent-lifecycle-methods-in-c-69a9f9371c15