[SalesForce] connectedCallback/disconnectedCallback not firing on 2nd display

I've came across several cases where these callbacks did not fire.

For example

  • Standard action override (new). Overridden with LAC component containing LWC component. Then navigation back on list view and on second navigation to the component just disconnectedCallback was triggered and component have not showed up.
  • Quick Action with LAC navigating (using navigationMixin) to lightning:isUrlAddressable component containing LWC component. Then navigating to even different record, on second redirect to that component, not connected nor disconnected callbacks were triggered and component in old state was displayed
  • VF Page on List View, storing selected Ids, then redirecting to URL of the lightning:isUrlAddressable LAC component which contains LWC component(s). Then navigating to the list view and on second redirect not connected nor disconnected callbacks were triggered and component in old state was displayed.
  • and possibly few more cases on edit action and so on.

NOTE: for any of them renderedCallback and constructor have not run either on second display.

Best Answer

For first case (Standard Action Override (new)), where just disconnected callback run on second redirect to that target, fix was easy.

  • wrap LWC component with div or any element: <div><c:lwc_component><c:lwc_component/></div>
  • NOTE: there is possibility to run eval("$A.get('e.force:refreshView').fire();"); on disconnectedCallback but you will lose reusability, because if you use this kind of component somewhere else and it will be conditionally rendered, it will fire refreshView on disconnecting from DOM.

Reason behind it is this: Aura framework doesn't render component into DOM if it is empty. As content on 2nd attempt was refreshing disconnectedCallback was run and was removed from DOM to be later again added in fresh state. But because of Aura framework found out that that component was removed and it was the only element inside that LAC, it hid that LAC component and that is the reason why connectedCallback didn't run as parent component was removed from DOM.

The second and third case is bit more tricky. State of lightning:isUrlAddressable component is cached and even with different parameters provided to it, it doesn't notice the change, even thou you have init function on it and even passes some attributes into LWC, it just doesn't run. So one way to force it to refresh is:

  • for lightning:isUrlAddressable component to implement onchange action for v.pageReference which will run $A.get('e.force:refreshView').fire();