← Back to Angular, page 7

angular-0128 · Medium mid

What is a RouteReuseStrategy, and how would you write one that keeps the state of a list page when the user goes to a detail page and back?

By default the router destroys a component when you navigate away and creates a new one when you come back. A custom RouteReuseStrategy can detach the component tree for chosen routes and store it, then attach it again when the user returns, which preserves scroll position and filters. You choose the routes with route data.

Full answer

The router asks a RouteReuseStrategy five questions during every navigation:

  1. shouldReuseRoute(future, current): should the current component be reused for the new route? The default returns true only when the route config is the same.
  2. shouldDetach(route): when leaving a route, should its component tree be stored instead of destroyed?
  3. store(route, handle): store the detached tree.
  4. shouldAttach(route): when entering a route, do we have a stored tree?
  5. retrieve(route): return the stored tree to attach.

Implementation for a list page:

  • Mark routes with data: { reuse: true }.
  • shouldDetach returns true for those routes.
  • store saves the handle in a Map using a key, the route path (or route.routeConfig.path).
  • shouldAttach returns true if the map has the key.
  • retrieve returns the saved handle.
  • shouldReuseRoute keeps the default: future.routeConfig === curr.routeConfig.

Provide it with { provide: RouteReuseStrategy, useClass: AppReuseStrategy }.

Cautions:

  • A detached component is not destroyed. Its subscriptions and timers keep running and its memory stays. Pause work in the component using the router (there are no "deactivate" lifecycle hooks, so listen to router events or use ngOnDestroy carefully: it is not called on detach).
  • Stale data. A stored list shows old data on return. Refresh on NavigationEnd when the route is reattached, or set a time limit for stored entries.
  • Clear the store on logout. Otherwise the next user could see the previous user's data. This is also a privacy problem.
  • Parameterised routes need a key that includes the params if each should be cached separately, and a cap on how many to keep.
  • A simpler alternative for many cases is to keep the filters in the URL query params and the data in a cache service. This survives refresh and is easier to reason about.
typescript
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';

export class AppReuseStrategy implements RouteReuseStrategy {
  private readonly stored = new Map<string, DetachedRouteHandle>();

  private key(route: ActivatedRouteSnapshot): string {
    return route.routeConfig?.path ?? '';
  }

  shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === current.routeConfig;
  }

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data['reuse'] === true;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
    if (handle) {
      this.stored.set(this.key(route), handle);
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return route.data['reuse'] === true && this.stored.has(this.key(route));
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return this.stored.get(this.key(route)) ?? null;
  }

  clear(): void {
    this.stored.clear(); // call on logout
  }
}

// providers: [{ provide: RouteReuseStrategy, useClass: AppReuseStrategy }]
// routes:    { path: 'students', component: StudentListComponent, data: { reuse: true } }

Angular 20.3, type-checked. The strategy is compiled against the router types, but it was not run in a Karma test here.

Key points

  • `RouteReuseStrategy` has five methods: reuse, detach, store, attach, retrieve.
  • Mark cacheable routes with `data`, store handles in a map, and provide the strategy with DI.
  • Detached components stay alive, so pause work, refresh stale data, and clear on logout.
  • Often URL params plus a cache service are simpler.

Common mistakes

  • Expecting `ngOnDestroy` to run when a component is detached.
  • Caching without clearing the store on logout.
  • Caching routes with parameters under one key.

Follow-ups

  • How would you limit the cache to five entries?
  • How do you refresh data when a cached page is shown again?
  • When would URL state be better than caching components?

Tips

  • List the five methods in order of use.
  • Mention privacy and stale data. Those are the real risks.
  • Offer the URL state alternative.

Evaluation rubric

  • Knows the strategy methods and their roles.
  • Writes a working cache for chosen routes.
  • Lists the risks and alternatives.