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 class. These methods are
shouldDetach
,store
,shouldAttach
,retrieve
, andshouldReuseRoute
. - Register your custom RouteReuseStrategy in the
app.module
file of your application.
The default BaseRouteReuseStrategy
class
Angular uses a default implementation of RouteReuseStrategy which does not cache any route. For more information about this class, checkout the documentation.
Implement the shouldAttach
method
Angular calls this method and passes a route as the parameter to determine whether it should retrieve the route from the cache or create a new one. If shouldAttach
returns true, Angular will retrieve the cached route by calling the retrieve
method. If shouldAttach
returns false, it will create a new route from scratch. In my code, I use a dictionary-like data structure to store cached routes. In the…