Skip to main content
Schedules a function to run as soon as the component has been mounted to the DOM. Like $effect, but the provided function only runs once.

Signature

fn
function
required
A function to run once the component is mounted. If a function is returned synchronously, it will be called when the component is unmounted.

Usage

onMount must be called during the component’s initialisation (but doesn’t need to live inside the component; it can be called from an external module).

Cleanup function

If a function is returned synchronously from onMount, it will be called when the component is unmounted:

Async functions

onMount can accept async functions, but the cleanup function must be returned synchronously if needed:

Server-side rendering

onMount functions do not run during server-side rendering. If you need to run code on both the server and client, use $effect instead.

Notes

  • Must be called during component initialization
  • Only runs once per component instance
  • Does not run during SSR
  • Can be called from external modules
  • Cleanup function must be returned synchronously