Let’s take a look at some key best practices you should follow as a Salesforce Lightning Developer.
- Server Calls:
Avoid server calls wherever you can. Use Lightning Data Service, use recordViewForm, editForm or even record:Data to play around the data without having to use server side controllers.
Try and ensure you use as much of SLDS as you can in your code. It is supported by Salesforce, doesn’t need maintenance for releases, is responsive automatically. Avoid writing custom CSS or inline CSS and keep it for scenarios where there’s nothing SLDS can do. Managing CSS can later become a pain.
It’s definitely important to use the console to understand JS errors but it’s also important that we clear out logs from our code as they take unnecessary heap space and impact handler performance. Once you are done debugging, erase the logs from the system which were put to test.
- Unbound Expressions:
If you have a parent child component dependency and you don’t want your attributes to be synced at both levels, you can use unbound attributes/expressions instead of the regular bound expressions which are synced every time even if its not needed. This needs additional event listeners that are internal working all the time to sync your data.
- Debug Mode:
Salesforce goes crazy slow if you have Debug Mode enabled. So, avoid enabling it for last resorts and do not enable it in Production at all.
- Modularisation & Coupling:
A single module should be like a utility that can be reused. Always design your components keeping in mind that you might need it as a stub for another component in future. Putting all the eggs in one basket has never helped anyone. Segregate modules based on what they should be doing.
- Lazy Loading:
Do not proactively load data that is not being used or may not be helpful for the user on the client side.
Cache data wherever possible. It helps in reducing trips and optimises speed. Use Lightning Data Service as it supports caching.
- Conditional Rendering:
Use <aura:if> tags along with boolean flags to lazy load templates or sections of your component, so that component instantiation is faster. If the aura if tag evaluates to false, the template is not created as part of the DOM, which saves time and improves speed.
- Event handling:
Use Component Events for Child-Parent propagation. Use attributes on parent or use aura:method for Parent-Child propagation. Avoid Application Events if possible and limit it only for application level communication.
- Unwanted JS libraries:
Remove and clear out unwanted static libraries that you might have used but are not being used by the DOM at all. They take up additional heap space and delay component initialisation. If you might need them in the future, let them be defined, but ensure you use minified versions for the same.
Lightning Best Practices
Want to understand all the points discussed above? Take a look at the video