Lifecycle

onSettled (formerly onMount)

Edit this page

Registers a method that runs after initial rendering is done and the elements have settled on the page. Ideal for using refs and managing other one-time setup.

import { onSettled } from "solid-js"
function onSettled(fn: () => void | (() => void)): void

onSettled is equivalent to a non-tracking effect -- a createEffect with no dependencies.

Key differences from onMount (Solid 1.x)

  • Cleanup support: onSettled can return a cleanup function that will be called when the owning scope is disposed.
  • No nested reactive primitives: You cannot create nested reactive primitives (such as signals, effects, or memos) inside the onSettled callback.

Usage

Accessing a ref after render

import { onSettled } from "solid-js"
function MyComponent() {
let ref: HTMLButtonElement
// when the component has settled, the button will be disabled
onSettled(() => {
ref.disabled = true
})
return <button ref={ref}>Focus me!</button>
}

Returning a cleanup function

Unlike onMount in Solid 1.x, onSettled supports returning a cleanup function. This cleanup function runs when the owning scope is disposed (e.g., when the component unmounts).

import { onSettled } from "solid-js"
function JsonViewer(props) {
let ref: HTMLDivElement
onSettled(() => {
const editor = initThirdPartyEditor(ref)
// cleanup: destroy the editor when the component unmounts
return () => {
editor.destroy()
}
})
return <div ref={ref} />
}

Migration from Solid 1.x

To migrate from onMount to onSettled:

  1. Replace all imports of onMount with onSettled:
// Before (Solid 1.x)
import { onMount } from "solid-js"
// After (Solid 2.0)
import { onSettled } from "solid-js"
  1. Replace all calls to onMount with onSettled:
// Before (Solid 1.x)
onMount(() => {
console.log("mounted")
})
// After (Solid 2.0)
onSettled(() => {
console.log("settled")
})
  1. If you previously created reactive primitives inside onMount, move them outside:
// Before (Solid 1.x) -- allowed nested reactive primitives
onMount(() => {
const [value, setValue] = createSignal(0) // this worked in 1.x
})
// After (Solid 2.0) -- reactive primitives must be created outside
const [value, setValue] = createSignal(0)
onSettled(() => {
// use value() and setValue() here, but do not create them here
})
  1. Optionally, take advantage of the new cleanup return value to simplify your code:
// Before (Solid 1.x)
onMount(() => {
const handler = () => console.log("resize")
window.addEventListener("resize", handler)
onCleanup(() => window.removeEventListener("resize", handler))
})
// After (Solid 2.0) -- return cleanup directly
onSettled(() => {
const handler = () => console.log("resize")
window.addEventListener("resize", handler)
return () => window.removeEventListener("resize", handler)
})
Report an issue with this page