Runs once when the component initializes. Signal accesses inside are not tracked.
import { onMount } from '@barefootjs/dom'
onMount(fn: () => void): void#Basic Usage
onMount(() => {
console.log('Component initialized')
})Unlike createEffect, this function never re-runs. It executes once at initialization time.
#Common Patterns
#Reading browser state
onMount(() => {
const hash = window.location.hash
setFilter(hash === '#/active' ? 'active' : 'all')
})#Setting up event listeners
onMount(() => {
const handleHashChange = () => setFilter(getFilterFromHash())
window.addEventListener('hashchange', handleHashChange)
onCleanup(() => window.removeEventListener('hashchange', handleHashChange))
})#Focusing an element
onMount(() => {
inputElement.focus()
})#How It Works
onMount is equivalent to:
createEffect(() => untrack(fn))The function runs inside an effect context (so onCleanup works), but untrack prevents any signal reads from being tracked as dependencies.
#`onMount` vs `createEffect`
onMount |
createEffect |
|
|---|---|---|
| Runs on init | Yes | Yes |
| Re-runs on signal change | No | Yes |
| Tracks dependencies | No | Yes |
Supports onCleanup |
Yes | Yes |