6

I need to detect when the LWC is destroyed, so far I haven't noticed that a disconnectedCallback has ever triggered on the LWC that is used in Screen on Flow. This creates a lot of problems because I want to unregister pubsub listeners on disconnectedCallback. Surprisingly, disconnectedCallback is not triggered even when the user leaves the flow and goes to a completely different page on community.

2

Its slightly tricky. disconnectedCallback is only called if a component is removed from the DOM, and this depends on the experience you are in.

  1. Lightning Experience keeps the 5 previous pages you've visited alive to provide instant backward navigation (using the browser's back button). So in LEX if you navigate away from a page or record to a different page, the page isn't destroyed, so your LWC is also not destroyed. Once you navigate to the 6th page, then the 1st page you visited is destroyed and disconnectedCallback is called. It is also important to remember that if you're re-visiting any of the 5 pages that are alive (using the browser back button), connectedCallback is not called again. However, if you go to a page by clicking its tab or link, the page would destroy and re-create the components.

  2. In Communities/Experience Cloud however, a page is destroyed when you navigate away to a different tab (not browser tab). So disconnectedCallback is immediately called.

  3. In Flow Runtime, a component is disconnected whenever you navigate away from that screen.

I just personally tried using an LWC in both the community and flow, and disconnectedCallback from both the flow screen component and page-level component are called when I navigate away to a different community page.

Now in cases where disconnectedCallback isn't called when you want, there is a workaround you can use: You can query for an element in your HTML template thats always shown to the user i.e., not within any if:true or if:false directives, and check it's height and width. For example

this.template.querySelector('div').offsetWidth

If their height and width are non-zero, that means your component is visible to the user. If it is 0, it means your component is not visible to the user (meaning that they navigated away from the page on which it is shown). Depending on this, you can perform steps like unregistering listeners. You may have to put this logic inside a setInterval block to keep checking for component visibility to re-connect listeners. So your logic to connect/disconnect from pubsub lives both inside connected/disconnectedCallback and the setInterval function.

I also made a short video explaining this concept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.