Why Components Persist During Navigation in Lightning?

Question:
In Salesforce Lightning Experience, I have custom Lightning pages and apps, both overriding default record views and serving as standalone pages accessed from the sidebar. However, when navigating from one tab to another, the components seem to only be hidden rather than destroyed. Upon navigating back to the tab, the components are recreated, which causes multiple instances of the same component to exist simultaneously.
For example, we have a component that registers for an app event. Every time the user navigates away and back, the event handler gets registered again, causing the handler to be fired multiple times as the same handler accumulates with each tab switch. After several tab switches, there can be dozens of event handlers firing simultaneously.
Has anyone encountered this issue? Any suggestions or workarounds?
Here’s the component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
<aura:handler event="c:BoringAppEvent" action="{!c.test}"/>
hi
<ui:button press="{!c.onClick}" >App Event</ui:button>
</aura:component>
And the controller:
({
test : function(component, event, helper) {
console.log('Clicked');
},
onClick : function(cmp, evt){
var notEvt = $A.get('e.c:BoringAppEvent');
notEvt.fire();
}
})
Renderer:
({
unrender: function(){
this.superUnrender();
console.log('unrender');
debugger;
}
})
Answer:
The issue arises because Lightning Experience caches the last few pages for faster navigation, keeping up to five history entries in memory. When you navigate between tabs, instead of destroying the previous page’s components, it simply hides them. The components are only destroyed when the browser’s back button is used to navigate.
CRS Info Solutions provides expert Salesforce training in Nagpur with real-world projects, certification support, and career-focused guidance.
The relevant code from app.js
explains this caching behavior:
/**
* sets the body of the content part of the center stage, and make sure we only keep this.MAXSTAGESLIDECOUNT (5) in
* memory at the same time
*/
setContentBody: function(component, content, body) {
if (body.length > this.MAXSTAGESLIDECOUNT) {
var skipped = body.splice(body.length - 2,1)[0]; //destroy previous to the last
skipped.destroy(true);
component._skipped++;
content.set("v.body", body);
}
}
Explanation:
The setContentBody
function manages the content of a central stage in Salesforce Lightning by limiting the in-memory history stack to a maximum of five entries (MAXSTAGESLIDECOUNT
). If the stack exceeds this limit, it removes and destroys the second-to-last entry to free memory, ensuring efficient navigation handling.
The key takeaway here is that Lightning tries to optimize performance by caching the last few views, and when navigating back to a previous view, it retrieves the component from the history stack instead of recreating it. This can lead to multiple handlers being registered if components are not properly destroyed.
To mitigate this issue, you can implement some workarounds:
1.Global Handler Registration:
When initializing your component with the event handler, register it globally so you can check if the handler is already registered before processing the event. This ensures only one handler is active at a time:
$A.theOneTrueHandler = cmp;
In the event handler, check if the handler matches:
if (cmp === $A.theOneTrueHandler) {
// Handle the event
}
2.Pass an ID from Parent to Child:
Pass a unique ID from the parent component to the child components. The child components can then check if the ID matches before handling the event. While this works, it can lead to cluttered code and is not the most efficient solution.
3.Use Component Events Instead:
If possible, consider switching to component events instead of application events. Component events are more isolated and don’t suffer from the issue of accumulating handlers like application events.
By using one of these strategies, you can prevent the issue of multiple event handlers being registered and firing unnecessarily.
Accelerate Your Career with Salesforce Training in Nagpur
Unlock the doors to a rewarding career with our Salesforce training in Nagpur! Our program is carefully crafted to provide you with expert-level certification guidance, in-depth interview preparation, and a comprehensive curriculum covering essential tracks like Admin, Developer, and AI. With detailed class notes and practical hands-on experience, you’ll gain the skills necessary to excel within the Salesforce ecosystem.
Our Salesforce training offers more than just theoretical knowledge. Experience personalized mentorship, industry-focused projects, and expert-led sessions to prepare you for real-world challenges. Whether you’re just starting or looking to upskill, our program ensures you’re equipped to thrive in a competitive job market.
Join us today and take the first step towards mastering Salesforce and shaping your professional future!!!