onSettled (formerly onMount)
Edit this pageRenamed in Solid 2.0
onMount has been renamed to onSettled in Solid 2.0. The onMount export is no longer available. If you are migrating from Solid 1.x, update all usages of onMount to onSettled.
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)): voidonSettled is equivalent to a non-tracking effect -- a createEffect with no dependencies.
Key differences from onMount (Solid 1.x)
- Cleanup support:
onSettledcan 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
onSettledcallback.
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:
- Replace all imports of
onMountwithonSettled:
// Before (Solid 1.x)import { onMount } from "solid-js"
// After (Solid 2.0)import { onSettled } from "solid-js"- Replace all calls to
onMountwithonSettled:
// Before (Solid 1.x)onMount(() => { console.log("mounted")})
// After (Solid 2.0)onSettled(() => { console.log("settled")})- If you previously created reactive primitives inside
onMount, move them outside:
// Before (Solid 1.x) -- allowed nested reactive primitivesonMount(() => { const [value, setValue] = createSignal(0) // this worked in 1.x})
// After (Solid 2.0) -- reactive primitives must be created outsideconst [value, setValue] = createSignal(0)onSettled(() => { // use value() and setValue() here, but do not create them here})- 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 directlyonSettled(() => { const handler = () => console.log("resize") window.addEventListener("resize", handler) return () => window.removeEventListener("resize", handler)})