onMount and onUnmount are Solar’s lifecycle hooks. onMount runs a callback once after the component’s first render, making it the right place for one-time setup like analytics events or imperative DOM initialization. onUnmount registers a cleanup callback that runs when the component is removed from the tree.
onMount
Solar queues fn as a microtask after the first render and calls it exactly once. Subsequent re-renders do not trigger it again.
// example
onMount(() => {
analytics.track('UserCard mounted')
document.title = 'User Profile'
})
onUnmount
Solar stores fn as the component’s cleanup callback and calls it when the component is unmounted from the DOM.
// example
onUnmount(() => {
analytics.track('UserCard unmounted')
subscription.cancel()
})
Using both in a component
const PageView = defineComponent({
name: 'PageView',
props: { page: { type: 'string', required: true } },
render({ page }) {
onMount(() => {
analytics.track('page_view', { page })
})
onUnmount(() => {
analytics.track('page_leave', { page })
})
return createElement('div', {}, page)
},
})
onMount only runs once — after the component’s first render. Re-renders do not trigger it again. If you need to run logic in response to a prop change, use useMemo with the changing prop as a dependency.
onUnmount registers its callback on every render, but the callback only runs once, when the component is actually removed. The last-registered cleanup function wins. In practice, register the same cleanup callback every render so the behavior is consistent regardless of how many times the component re-renders before unmounting.
vs. useSubscription
For event listeners specifically, prefer useSubscription over onMount/onUnmount. useSubscription handles attaching and detaching automatically whenever the source, event name, or handler changes — something you would have to implement manually with lifecycle hooks. Reserve onMount and onUnmount for genuinely one-time setup and teardown logic, such as analytics calls, timers, or imperative integrations.