New Way to Cache in Lightning Components

One of the best ways to gain performance in your Lightning pages is through caching. I have spoken and written about how one Lightning best practice is to use Storable Actions. File_Server_Cache_BlueThis means data served up from your server side actions is cacheable and after they are accessed the first time, they are super fast to render a second or third time. This is still a best practice, but what I wanted to make you aware of was that there is a new and even easier way to get the best of caching.

And, the best part is that you can get the benefits of caching using this technique for both your Aura components and any new Lightning web components you might create.

Prior to the Winter 19 release, if you wanted to cache data you had to call setStorable() for every action that called your apex method, such as in this example:

​var action = component.get('c.getRacesDB');
​action.setStorable();
​action.setCallback(this, function(response) {
​            // Code here to handle the response
​}
​$A.enqueueAction(action);

In the code above, I am making a call to an apex method named getRacesDB, and this will return to me a list of race data. To make that data cacheable, I only have to add the line of code that marks the action as setStorable. Even though this is only a single line of code, if I had multiple places that needed to call the getRacesDB method (which is very likely in a large and complex application), the setStorable line of code would have to be repeated.

With Winter 19 and the API version of 44.0 or greater, you can simply annotate your @AuraEnabled apex method with the cacheable=true attribute. You no longer need to use setStorable. For example, if I wanted to make getRacesDB method cacheable, I would just add the cacheable=true attribute and the data it returns will be cacheable for any actin that calls it.

public with sharing class ListRacesController {

    @AuraEnabled(cacheable=true)
    public static PageResult getRacesDB(Decimal pageSize, Decimal pageNumber) {
        // Code to return the list of races goes here

Just make sure to remember to use API version 44.0 and above when using this new attribute.

2 comments

  1. Nice tip! Additionally, the @AuraEnabled( cacheable = true ) feature is a good way to cache results of methods used by Lightning Web Components as I’m not sure there’s any other way to say the method call would be cached client-side otherwise (without implementing your own client-side caching mechanism).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s