Skip to content

useMount

Runs logic once when the component mounts.

Runs logic once when the component mounts.

Import

import { useMount } from '@kamod-ch/hooks'

Live demo

Basic demo

Runs logic once when the component mounts.

Mount count: 1

Mounted child content.

import { useState } from 'preact/hooks'
import { useMount } from '@kamod-ch/hooks'

function Child({ onMount }: { onMount: () => void }) {
  useMount(onMount)
  return <p>Mounted child content.</p>
}

export default function UseMountDemo() {
  const [visible, setVisible] = useState(true)
  const [mounts, setMounts] = useState(1)

  return (
    <div>
      <p><strong>Mount count:</strong> {mounts}</p>
      <button type="button" onClick={() => setVisible((value) => !value)}>{visible ? 'Unmount' : 'Mount'}</button>
      {visible ? <Child onMount={() => setMounts((value) => value + 1)} /> : null}
    </div>
  )
}

API

TypeScript signature
import type { EffectCallback } from '../utils/types-compat.js';
type MountCallback = EffectCallback | (() => Promise<void | (() => void)>);
declare const useMount: (fn: MountCallback) => void;
export default useMount;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.