Why does cached data disappear when using forceLoad in a Blazor app?

Obakeng Aphane 20 Reputation points
2025-09-30T13:59:18.2166667+00:00

In a Blazor application, cached results are stored using IMemoryCache through a CacheMemory wrapper. When navigating to another page with NavigateTo(forceLoad: true), the destination page does not have access to the cached data. However, when navigating with forceLoad: false, the cached data remains accessible. The app is utilizing Interactive Auto Rendering.

Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 3,500 Reputation points Microsoft External Staff
    2025-10-01T07:33:35.6+00:00

    Hi @Obakeng Aphane ,

    When you call NavigateTo(..., forceLoad: true), you trigger a full browser page load. That tears down the current Blazor runtime, so anything held only in memory—like your IMemoryCache in a WASM (or client-hydrated InteractiveAuto) session—is lost.

    Summary:

    • forceLoad: false: SPA navigation, runtime stays alive, in‑memory cache survives.
    • forceLoad: true: full reload, new runtime, in‑memory cache emptied.

    If you need certain values to survive a hard reload, mirror them into browser storage and rehydrate them on startup.

    LocalStorage vs SessionStorage

    • localStorage: persists across tabs and browser restarts (until cleared).
    • sessionStorage: lasts only for the current tab (ends when tab closes).
    • Both store simple string key/value pairs (you JSON‑serialize objects).
    • Not secure for sensitive data (visible to the user; no encryption by default).
    • Size limits are small (a few MB), so store only what you must.

    Minimal pattern:

    1. Before navigation: serialize the values you care about.
    2. On app start (e.g., in OnInitializedAsync of a root/service): read, deserialize, and repopulate your in‑memory cache.
    // Save
    await js.InvokeVoidAsync("localStorage.setItem", "myCache", JsonSerializer.Serialize(cacheObject));
     
    // Load
    var json = await js.InvokeAsync<string>("localStorage.getItem", "myCache");
    if (!string.IsNullOrEmpty(json))
    {
        var restored = JsonSerializer.Deserialize<MyCacheDto>(json);
        // repopulate your cache
    }
    

    Doc starting points:

    Hope this helps. Let me know if you need any help.

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 81,191 Reputation points Volunteer Moderator
    2025-09-30T15:14:52.0033333+00:00

    Auto render means you running the blazor app as a WASM with server pre-render. When you set forceReload to true, the browser unloads and reloads the app. As the memory cache is in the browser WASM, it is lost on the reload.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.