Hook into "On Page Leave" with custom code

I’m creating a custom UI component. Within my component code, I want to register a handler which is called when the user leaves the page (by approuter navigation or browser back). This handler should do some internal cleaning-up/garbage collection.

There is the standard UI-Builder event “On Page Leave”, but I don’t want that consumers of my component have to code something in there. My cleaning-up shall work out of the box.

Now my question: Is there a piece of javascript code which you can suggest to register such a handler? Still, a consumer of my component shall be able to fill something into “On Page Leave Handler” without interfering with my handler.

I tried things like window.onbeforeunload and window.onunload without success. Maybe I need to do something specific to the React framework?

Regards,

Hi @Klaas_Klever

Do you need a handler when your customer leaves the page or when the custom component is unmounting? Unmounting means when a component is removed from the place where it’s used, for instance, you’ve got the following structure:

 - Page 
    |- Block
       |- YourCustomComponent

and you toggle visibility for the Block component, when the Block is hidden all the inner components (YourCustomComponent) unmount and they are not on the scene anymore

For our built-in component, there are OnBeforeMount OnMounted and OnBeforeUnmount lifecycle handlers, so perhaps you are looking at how to create them in your custom components

Also, when a customer leaves a page it unmounts all the components on the page

Alright!
So, how do I define a handler for onBeforeUnmount for my component?
Can you share a javascript snippet?

Thanks

On BeforeMount Handler

 React.useMemo(() => {
    // run your handler here
  }, [])

On Mounted Handler

  React.useLayoutEffect(() => {
    // run your handler here
  }, [])

On BeforeUnmount Handler

  React.useEffect(() => {
    return () => {
      // run your handler here
    }
  }, [])

Cool! Got the OnBeforeMount running! I think I have to learn more about React components :thinking: :grimacing:

As always - great support! :clap:

Regards,