Detecting render mode at runtime
Understanding where and how your component renders is crucial for optimizing performance and tailoring user experience. Blazor allows you to detect the render location, interactivity, and assigned render mode at runtime. You can query whether the component is operating in an interactive state or just prerendering. These insights open up new possibilities for debugging, performance optimization, and building components that adapt dynamically to their rendering context.
Let’s hide the area with tickets in the Offer
component to prevent user interactions, such as adding tickets to the cart, until the component is ready and interactive.
Getting ready
Before you explore render mode detection, do the following:
- Create a
Recipe04
directory – this will be your working directory - Copy the
Offer
andTicket
components from the Declaring parameters on a component recipe or copy their implementations from theChapter01
/Recipe03
directory of this book’s GitHub repository
How to do it...
Follow these steps:
- Navigate to the
Offer
component and update the path attached to the@page
directive to avoid routing conflicts:@page "/ch01r04" @rendermode InteractiveWebAssembly
- Below the component directives, add some conditional markup to indicate that the component is getting ready based on the value of the
RendererInfo.IsInteractive
property:@if (!RendererInfo.IsInteractive) { Â Â Â Â <p>Getting ready...</p> Â Â Â Â return; } @* existing markup is obscured, but still down here *@
How it works...
In step 1, we navigated to the Offer
component and updated the path that was assigned to the @page
directive. Blazor doesn’t allow duplicated routes, so we triggered a conflict since we copied the Offer
component with a route from the Declaring parameters on a component recipe.
In step 2, we introduced a conditional markup block below the component directives. We leveraged the RendererInfo
property that the ComponentBase
class exposes, allowing us to track the component rendering state. The RendererInfo
property has two properties:
- The
RendererInfo.Name
property tells us where the component is currently running and returns the following options:Static
: This indicates that the component is running on the server without any interactivityServer
: This indicates that the component is running on the server and will be interactive after it fully loadsWebAssembly
: This indicates that the component is running in the client’s browser and becomes interactive after loadingWebView
: This indicates that it’s dedicated to .NET MAUI and native devices
- The
RendererInfo.IsInteractive
property shows whether the component is in an interactive state or not (such as during prerendering or static SSR)
We leveraged the RendererInfo.IsInteractive
property to detect whether the interactivity is ready. If it isn’t, we display a Getting ready... message to inform users they should wait.