Why you should be using the Lightning Data Service whenever possible

If you are creating Lightning components and working with a single record of data, you should be using the Lightning Data Service (LDS) or the force:recordData tag.

And for those of you that have not heard about the LDS, you can think of it as the standard controller for lightning components. It is similar to the standard controller used in Visualforce in that it gets you access to your orgs data, but without the need to write any Apex or SOQL and that is a pretty cool thing because when you don’t have to worry about writing Apex, you also do not have to worry about FLS or Field Level Security and CRUD or Create Access Update and Delete security, which is something you would have to specifically check for in your code if you did not use the Lightning Data Service.

You see I have to tell you that all of you Visualforce developers have been a bit spoiled when it comes to security, b/c in most cases, the pages that you wrote did not have to specifically check for these permissions (even when they used controllers). But, the Lightning Platform works very differently than Visualforce and any Apex code you write does have to do these checks, which involves writing more code.

With the Lightning Data Service, you also get other built-in features like auto-notifications when there are record changes, as well as offline access for Salesforce1.

And if all that was not enough to convince you that Lightning Data Service is something you want to use, here is one more really big reason. Even if you have multiple components using the Lightning Data Service, they are all going to use a single request and deal with a cached response and in terms of performance this is huge.

Even if you have multiple components using the Lightning Data Service, they are all going to use a single request and deal with a cached response

So let’s talk about that a bit more. Let’s say you have two components that are using the force:recordData tag. Each one will make a request for data through the Lightning Data Service Controller, and those requests will be funneled into one single request which is sent to the Salesforce server, such as you see here.

LDSDemo2

But what is returned is a response that will be stored in a shared data cache and also returned back to the two components that started all this, such as in the diagram below. And this means that not only will those two components be able to retrieve the data faster than two components that were using their own apex controllers

LDSDemo3

But if a third component that needed that same data were to come along, it would be able to get a cached response almost immediately without even having to make a call to the server. Boom!

LDSDemo4

And the beauty of it all is that you can implement this with just a few lines of markup code in the component and then a few more lines in the JavaScript controller to load and save the record. You do not have to write any Apex or SOQL code to implement this, but you get all the performance benefits.

So now do you see why you need to be using the Lightning Data Service whenever possible?

If you found this article useful, you might want to checkout my latest course on Pluralsight titled, Lightning Component Development Best Practices, where I talk about the Lightning Data Service and a lot more.

 

5 Ways to Build Lightning Fast Components

This post is based on a talk I gave twice at this years Dreamforce.

The five tips I cover here were hand picked by me out of a whole bunch of stuff I discovered while creating my latest Pluralsight course about Lightning Best Practices. The course will be released soon, so stay tuned and I will let you know. All of these tips are pretty simple to implement and I think they represent the quickest and easiest things you can do to get better performance.

So, in David Letterman style. here they are from last to first:

# 5 – Check your Settings

Specifically, you want to check the values for debug mode and component caching, which should have different values depending on whether you are in production versus development.

Debug Mode

Debug mode is what you can toggle to allow detailed debug messages to appear in your browsers console log and these messages can really help you not only to debug your components, but as you will learn about soon, they feature important messages about performance.

For the debug mode, you want that to be enabled in development, so you can get those messages you need as you are developing, but in production, you want to make sure this is turned off b/c when it is enabled, it means that all the css and javascript that is downloaded to the client is not minified, which means it will take longer to download and longer for your components to render and that is why you do not want it enabled in production.

DebugMode

Component Caching

Component caching has to do with whether pages will be cached to specifically improve performance, which is why that one is so important.

For the component caching, the settings should be the opposite and you want caching disabled in development, because while you are making changes to components and testing how they render, you do not want to have to hit your browser refresh several times before you see your changes which is what will happen if it is enabled. But, in production, where changes to the code are not happening, you want to make sure caching is enabled, since this will result in faster component rendering.

ComponentCaching

# 4 – Use <aura:if> for Conditional Rendering

To do conditional rendering in Lightning, you could use a technique known as css toggling and for a long time this was actually the way even Salesforce recommended you do toggling in the official docs. But in fact, what we now know is that you do not want to do this and the reason why is that when you use this method, any components inside the css toggled code (and most importantly any event handlers associated with those components) are rendered right away.

The alternative is to use the aura:if tag. Using this means that anything inside the aura:if will not actually be rendered until the condition is true. So in the example below, the event handlers associated with the lightning button will not be active until the aura:if condition is true.

<aura:if isTrue="{!v.isVisible}">
             <lightning:button label="Submit"
            onclick="{!c.newRecord}" />
 </aura:if>

# 3 – Check your Console Log

The number 3 tip is a reminder to always check your browsers console log because not only can you use this for debugging your components, but the lightning development team now will push performance warning messages to the console log and so even if your component is rendering fine and doing everything you want it to, you could have a performance issue and not even be aware of it.

PerformanceWarnings.png

You can access the Console log for the Google Chrome browser by right-clicking inside the browser and selecting Inspect. But know that these messages will only appear when debug mode has been enabled, so this is something you want to only check for in your development org.

# 2 – Use the Lightning Data Service whenever possible

The Lightning Data Service is just way cool and offers a whole bunch of great features. If you do not know about it, check out this great Trailhead that tells you all about how to use it.

The best thing about the Lightning Data Service (or <force:recordData> tag) is that it provides a single cached response and this can have a big impact on performance.

Let’s say you have three components that are all using the force:recordData tag. Each one will make a request for data through the Lightning Data Service Controller, and those requests will be funneled into one single request which is sent to the Salesforce server.

But what is returned is a response that will be stored in a shared data cache and also returned back to the two components that started all this. And this means that not only will those two components be able to retrieve the data faster than two components that were using their own apex controllers.

And if a third component that needed that same data were to come along, it would be able to get a cached response almost immediately without even having to make a call to the server. Boom!

LDS2

# 1 – Use Storable Actions whenever possible

So here we are at the number one tip and it is to use storable actions whenever possible, which essentially allows you to take advantage of caching and get all the benefits that you just saw demonstrated, even when you are not using the Lightning Data Service.

And a good example of this can be seen with a component that needs to access a list of data (which is something that the Lightning Data Service currently cannot handle, since it only works with a single record).

When paging through a list of records that use storable actions, after the pages are rendered once, the next time they are returned to, the rendering will happen in a fraction of the original rendering time. This can results in significant performance savings when a user needs to page through a long list of records.

And to take advantage of caching, all you have to do is add a single line of code right after you define the action, such as in the following example:

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

If you found this article useful, you might want to checkout my latest course on Pluralsight titled, Lightning Component Development Best Practices, where I talk about base lightning components and a lot more.

Lightning Data Service Goes Beta in Summer 17

For the past two Salesforce release cycles the Lightning Data Service (LDS) has been in developer preview, but starting in Summer 17, it moves to Beta. The biggest thing to be aware of is that if you have created any code using the LDS, the markup will need to be changed. Prior to Summer 17, the LDS used the force:recordPreview tag, but this has been replaced with force:recordData.

If you have created code using the Lightning Data Service when it was in preview and named force:recordPreview, you will have to change your markup before that code will work in a Summer 17 org.

So what is the LDS?  (you may be asking yourself)

The LDS is on it’s way to becoming the standard controller (used in Visualforce) equivalent for a Lightning Component. It makes working with data in a Lightning component super easy (as in all you need to do to use it is add a single line of markup code). No Apex code is needed.

Another thing that makes the LDS so cool is that all Lightning components that utilize the recordData tag will have access to a shared data cache. This ensures that they return data as quickly as possible.

LDS.png

If you have not yet checked out the Lightning Data Service (LDS), this is definitely the time to do so. And if you are interested in seeing an example of how a Lightning Component can be greatly simplified using the LDS, go over to Pluralsight and check out my latest course titled,  Customizing Salesforce with Lightning Components. I have an entire module dedicated to Working with Lightning Data Service.

New Customizing Salesforce with Lightning Components Course Released

SecondCourse.pngI am proud to announce that yesterday my new course for Pluralsight titled, “Customizing Salesforce with Lightning Components: Getting Started” was released.

Here is the long description:

In this course, you’ll learn how to easily customize Salesforce with the new Lightning Component framework, which includes all the tools and technologies needed to build responsive and efficient components for any device. First, you’ll cover the basics of building Lightning Components, and how to work with data using built-in components such as the Lightning Data Service. Next, you’ll explore Lightning alternatives for the traditional JavaScript buttons that so many orgs have now. Finally, you’ll learn about the most efficient way to migrate from Visualforce to Lightning. Although, many things have changed during the evolution of the Lightning Component framework, don’t worry, you’ll learn what you need to know to get up to “lightning” speed. By the end of this course, you’ll be well on your journey towards customizing your org with Lightning components.

Specific topics I cover are:

  • Base Lightning Components
  • Lightning Data Service
  • Extending SLDS
  • Lightning Actions
  • Migrating from Visualforce to Lightning

Hope you like the course. I worked really hard on it, dedicating every weekend for the past 7 months. I wanted each module to be special and I hope my efforts show.

If you see the course, I would be really interested in your feedback – good or negative. All of it helps me to create better courses.

Hello Lightning Data Service

The Winter 17 Salesforce release introduced a lot of exciting new changes for Lightning Component Developers. One of the most significant, was the release of the Lightning Data Service (LDS).

The LDS is “kind of” like the standard Visualforce controller, but for Lightning components. Even after the Spring 17 release, it remains in developer preview. This means you cannot use it for Production apps  and it will likely change names before it’s release. However, this represents the direction of where Lightning development is headed in terms of making it easier on the developer. Expect to see more things like this.

The LDS can be really cool if you are putting together a really simple component that will just access a single sObject and do some CRUD with it. The biggest benefit with using the LDS is that you do not need to use Apex code (think no unit tests). And most importantly, you do not have to include CRUD access checks in that code. You also get great performance benefits because components using the LDS all share a highly efficient local storage, so they should run faster.

Unfortunately, most of the Lightning component samples out there do not include Apex code to check for CRUD and FLS permissions and this is a big mistake because for Lightning components, this is not automatically enforced. CRUD and FLS security was automatically enforced in Visualforce pages, so most Salesforce developers will not even think about adding these checks. But in the world of Lightning, if you are using Apex code, you need to add access checks. Period!!!!

If you have no idea what I am even talking about, take a look at this sample Apex code, which includes the necessary access checks:

public with sharing class MyController {
  @AuraEnabled
  public static List getAccounts() {
    String [] accountAccessFields = new String [] {'Id',
      'Name',
      'AccountNumber',
      'AccountRevenue',
      'CreatedDate'
    };
    // Obtain the field name/token map for the Account object
    Map<String,Schema.SObjectField> m = Schema.SObjectType.Account.fields.getMap();

    for (String fieldToCheck : accountAccessFields) {

        // Check if the user has access to view field
        if (!m.get(fieldToCheck).getDescribe().isAccessible()) {

            // Pass error to client
            throw new System.NoAccessException()

            // Suppress editor logs
            return null;
         }
     }

     // Query the object safely. This is the only code you will see in most 
     // Lightning code samples that do not include the access checks
     return [SELECT Id, Name, AccountNumber, AccountRevenue, CreatedDate 
              FROM Account];
  }
}

By using the LDS, you avoid having to include ALL of this apex code and you still get a secure Lightning component. See now why using the LDS is so cool?

Now, I have to be honest and tell you that using LDS is not all unicorns and rainbows. It has some serious limitations (besides the fact that it is still in developer preview) such as:

  • Only works with a single record and does not support operations that need to go against multiple sObjects
  • Cannot be used to perform queries using anything other than the recordID.
  • Even after it is released, it will probably not work in Communities, Lightning Out or Lightning Components for Visualforce

Despite these limitations, I still think the LDS is cool and that it’s introduction indicates more good things to come. I hope you take the time to check it out.