wkkkis-hooks

use-on-mount (use-on-mount)

Execute a function when the component is updated, but not when it is mounted.

v0.1.0

Usage

import { use-on-mount } from "@/hooks"
1"use client"; 2 3import React, { useState } from "react"; 4 5import { 6 Card, 7 CardContent, 8 CardDescription, 9 CardFooter, 10 CardHeader, 11 CardTitle, 12} from "@/components/ui/card"; 13 14import { useOnMount } from "@/components/hooks/use-on-mount"; 15 16export function ExampleComponent() { 17 const [message, setMessage] = useState("Waiting for mount..."); 18 19 useOnMount(() => { 20 setMessage("The component has been mounted!"); 21 console.log("Component mounted!"); 22 }); 23 24 return ( 25 <Card className="max-w-sm w-full relative"> 26 <CardHeader> 27 <CardTitle>useOnMount</CardTitle> 28 <CardDescription> 29 This example uses the <code>useOnMount</code> hook to execute a 30 function only once when the component is mounted. 31 </CardDescription> 32 </CardHeader> 33 <CardContent> 34 <p>{message}</p> 35 </CardContent> 36 <CardFooter> 37 <p className="text-sm text-muted-foreground"> 38 Check console for more information. 39 </p> 40 </CardFooter> 41 </Card> 42 ); 43} 44

Install

npx wkkkis-hooks add use-on-mount

Options

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

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.

Files in this hook

SourceDestination
files/use-on-mount.tssrc/hooks/use-on-mount.ts