onMount
Lifecycle method run in the browser that registers a function that runs after the initial render and elements have been mounted. Ideal for using refs and managing other one-time side effects.
You can be confident that this method will run only once after initial rendering is done and won't run on the server.
It's an alias for an effect that is non-tracking, meaning that it is equivalent to a createEffect
with no dependencies.
While it can be used to perform data fetching, it is best to use Solid's resources with createResource
for that task.
TypeScript Function Signature
typescript
function onMount(fn: () => void): void;
typescript
function onMount(fn: () => void): void;
Example
Imagine we would like to attach an event listener to our window and listen to the resize event. We only want to attach it once, so onMount will be helpful in this case.
jsx
import { onMount } from "solid-js";const handleResize = () => {//...};const App = () => {onMount(() => {window.addEventListener("resize", handleResize);});};
jsx
import { onMount } from "solid-js";const handleResize = () => {//...};const App = () => {onMount(() => {window.addEventListener("resize", handleResize);});};