Lifecycle

onMount

Edit this page

onMount registers a function that runs once after the initial render for the current component or root.


Import

import { onMount } from "solid-js";

Type

function onMount(fn: () => void): void;

Parameters

fn

  • Type: () => void
  • Required: Yes

Non-tracking function executed once on mount.


Return value

onMount does not return a value.


Behavior

  • On the client, onMount runs once after the initial render. It does not run during server rendering.
  • fn does not track reactive dependencies.
  • Internally, onMount(fn) is equivalent to createEffect(() => untrack(fn)).
  • By the time onMount runs, refs have already been assigned.
  • Returning a function from fn does not register cleanup. Use onCleanup inside onMount when cleanup is needed.

Examples

Access a ref after mount

import { onMount } from "solid-js";
function MyComponent() {
let ref: HTMLButtonElement;
onMount(() => {
ref.disabled = true;
});
return <button ref={ref}>Focus me!</button>;
}

Run one-time browser setup

import { onMount } from "solid-js";
function Example() {
onMount(() => {
// Browser-only code
console.log(window.location.pathname);
});
return <div>Mounted</div>;
}

Report an issue with this page