Razor Component Lifecycle
Learn about the Razor component lifecycle.
In Blazor, each Razor component goes through specific lifecycle events before it’s displayed to the user. It's important to know how these events are handled and what can we do during each of these events, so we can apply additional logic if needed.
To demonstrate how Razor lifecycle events work, we have the following setup where we applied such events:
<Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> <FocusOnNavigate RouteData="@routeData" Selector="h1" /> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router>
The lifecycle events are handled by methods from the ComponentBase
class that any Razor component inherits from. To apply custom logic during any of these events, we can override the method that corresponds to the specific event and insert the logic into it.
Razor lifecycle events
Most of these methods have a synchronous and asynchronous version. Both versions are equivalent. The choice of one over the other depends on whether or not we would want to call any asynchronous code in the method.
In the setup above, ...