Cache angular components using RouteReuseStrategy

Tai Bo
6 min readApr 8, 2023

The project I have worked on has several pages that load data in Angular Material tables. The application’s user interface consists of a left menu with multiple tabs, and clicking on each tab loads the corresponding component and its child on the right. However, initializing the component appears to be an expensive operation, as it takes time to load the parent and child components and initialize the Material table, especially when there is a considerable amount of data to be displayed.

This delay causes the application to become unresponsive, especially when the user switches between tabs quickly, causing the components to pile up. I initially thought that the issue was related to fetching data through the network, but caching the data did not help to improve the performance.

After researching the topic of reusing components, I discovered the RouteReuseStrategy class. This class provides hooks for developers to advise Angular on when to reuse a route and how to cache a route. By utilizing this class, we can avoid the expensive process of destroying and initializing the components and displaying data in the table.

A typical solution for caching components in an Angular application involves the following steps:

  • Identify the components that you want to cache. You can do this when defining the routes in your application.
  • Create a class that implements the RouteReuseStrategy and override the five methods required by the abstract…

--

--

Tai Bo

Backend developer in .NET core. I enjoy the outdoor, hanging out with good friends, reading and personal development.