useMount
A hook to run a function when the component mounts
Installation
npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-mount.json"pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-mount.json"yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-mount.json"bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-mount.json"Copy and paste the following code into your project.
import { useEffect } from 'react'
import type { EffectCallback } from 'react'
type MountCallback = EffectCallback | (() => Promise<void | (() => void)>)
export function useMount(fn: MountCallback) {
useEffect(() => {
const result = fn?.()
// If fn returns a Promise, don't return it as cleanup function
if (
result &&
typeof result === 'object' &&
typeof (result as any).then === 'function'
) {
return
}
return result as ReturnType<EffectCallback>
}, [])
}API
type MountCallback = EffectCallback | (() => Promise<void | (() => void)>)
/**
* A hook to run a function when the component mounts
* @param fn - The function to run when the component mounts
* @returns The function to run when the component mounts
*/
export function useMount(fn: MountCallback): voidCredits
Last updated on