Svelte onMount return vs onDestroy

Similarities

Function returned from onMount and callback passed to onDestroy are both called before a Svelte component is unmounted(destroyed).

If a function is returned from onMount, it will be called when the component is unmounted. — onMount, Svelte Docs

Therefore, they can be used to clear intervals or remove event listeners.

Schedules a callback to run immediately before the component is unmounted. — onDestroy, Svelte Docs

Difference

onDestroy runs inside a server-side component. This affects SSR(server-side-rendering). Therefore in SvelteKit, it is advised to clear intervals and remove event listeners using onMount instead.

Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component. — onDestroy, Svelte Docs

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hyunbin

Hyunbin

Node.js and web developer using TypeScript. Undergraduate in Seoul National University.