
Caching API responses in Blazor WASM reduces network calls, speeds up the UI, and improves offline resilience.
// Program.cs
builder.Services.AddMemoryCache();
// In a service:
@inject IMemoryCache Cacheprivate async Task<List<Product>> GetProductsAsync()
{
const string key = "products_all";
if (!Cache.TryGetValue(key, out List<Product> products))
{
products = await Http.GetFromJsonAsync<List<Product>>(
"/api/products") ?? new();
Cache.Set(key, products, TimeSpan.FromMinutes(5));
}
return products;
}var options = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
.SetSlidingExpiration(TimeSpan.FromMinutes(2));Cache.Remove("products_all"); // Force refresh after mutationReference:
TaskLoco™ — The Sticky Note GOAT