Important: In development with React Strict Mode enabled, this hook may invoke its callback twice. This is intentional to flush side effects and will not occur in production builds, outside Strict Mode or in React 19 or above.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
callback | void 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);