Course contentsShow
← C#
Lesson 1399 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

UI Animation and Motion

Integrate web animations with C# lifecycle events for smooth visual transitions.

In this lesson, you will learn how to choreograph Blazor component transitions by anchoring CSS animations to C# component lifecycle events.

Synchronizing Motion with Lifecycle

In Blazor, "motion" isn't just about CSS keyframes; it’s about state synchronization. When a component enters the DOM, re-renders, or unmounts, there is a tiny window of time where the UI feels "jumpy" if the state update happens faster than the browser can render the change.

To create professional transitions, we tie our animations to the OnInitializedAsync or OnParametersSet lifecycle methods. By toggling a CSS class based on a boolean state (e.g., isLoaded), we signal the browser to trigger a transition precisely when our data is ready.

Practical Implementation

Consider a scenario where you want a list to fade in only after the data has been fetched from an API:

<div class="fade-container @(isLoaded ? "visible" : "hidden")">
    @foreach (var item in Items) { <p>@item</p> }
</div>

@code {
    private bool isLoaded;
    
    protected override async Task OnInitializedAsync() {
        var data = await DataService.GetDataAsync();
        // Trigger the animation by updating state
        isLoaded = true; 
        StateHasChanged();
    }
}

In your CSS, you define the motion:

.fade-container { transition: opacity 0.5s ease-in; opacity: 0; }
.fade-container.visible { opacity: 1; }

Why this matters

Using lifecycle hooks prevents "flicker"—the jarring visual snap that occurs when content is injected before the UI is ready to display it. Because StateHasChanged() informs the Blazor renderer that the UI tree has updated, the browser observes the addition of the .visible class and applies the transition logic in the very next paint cycle.

By keeping your animation triggers inside these events, you ensure that the motion is a reflection of your application state rather than just a static rule, making your UI feel responsive and intentional.

Key Takeaway: Use C# lifecycle methods as the source of truth to trigger CSS transitions, ensuring that UI motion remains perfectly synchronized with data availability.