Callback of destruction via onMount
The life cycle function onMount
agenda one callback to be executed once the component has been assembled in the FOD.
Optionally, if this callback return another function, this will be used as callback for the moment the component is being unmounted. It is executed when the component is unmounted.
A peculiarity of onMount
is that it does not run if Svelte is running on the server (in the context of the components server-side). Therefore, the disassembly function of the onMount
nay will be executed on the server side.
Callback of destruction via onDestroy
It’s basically the same as the previous one, but there are two differences.
Unlike the callback of destruction created by useMount
, which causes the destruction of the component, callback scheduled by onDestroy
is executed before that the disassembly even begins.
Therefore, onDestroy
will always be executed before of callback of destruction created by onMount
.
Another difference is that the onDestroy
is executed by components running on the server side. Therefore, they are required in some SSR-facing functionality.
Demonstration
I left an example in Svelte REPL.
Note that when the component is unmounted, messages on the console are printed in the following order:
- Component destroyed! (track
onDestroy
)
- Component destroyed! (track
onMount
)
This demonstrates the behaviour of the execution order described above.
Perfect! I only recommend replacing the word
construido
fordestruído
on the stretch within onMount:return () => console.log('Componente construído! (via onMount)');
why sometimes even the smallest things can cause confusion.– yoyo
@Yoyo, really, was a mess of mine. I meant "destroyed" even. Thanks for the warning. : ) Tomorrow I will delete my comment.
– Luiz Felipe