h3/use's logo

h3/use

Command Palette

Search for a command to run...

useOnMount

Execute a function only once when the component is mounted.

useOnMount
This example uses the useOnMount hook to execute a function only once when the component is mounted.

Waiting for mount...

Check console for more information.

Installation

Props

PropTypeDefaultDescription
callbackvoid function() => {}The function to execute when the component is mounted.

Key Features & Details

Execution Timing

  • The callback is executed only once, immediately after the component is mounted (on the client).
  • The callback will not run again on re-renders or updates.

Callback Stability

  • The callback is not re-invoked if it changes between renders; only the initial callback is used.
  • For best results, use a stable callback (e.g., from useCallback) if it depends on props or state.

SSR & Client-Only

  • The hook is client-side only; on the server, the callback is never called.

Best Practices & Caveats

  • Use for initialization logic, analytics, subscriptions, or side effects that should only run once.
  • Avoid side effects that depend on up-to-date props or state unless the callback is stable.

Examples

Basic Usage

useOnMount(() => {
  console.log('Component mounted!');
});

With Stable Callback

const onMount = useCallback(() => {
  // Initialization logic
}, []);
useOnMount(onMount);