use-did-update (use-did-update)
Execute a function when the component is updated, but not when it is mounted.
v0.1.0
Usage
import { use-did-update } from "@/hooks"
1"use client";
2
3import React, { useState } from "react";
4
5import { Button } from "@/components/ui/button";
6import {
7 Card,
8 CardContent,
9 CardDescription,
10 CardHeader,
11 CardTitle,
12} from "@/components/ui/card";
13
14import { useDidUpdate } from "@/components/hooks/use-did-update";
15
16export function UseDidUpdateDemo() {
17 const [count, setCount] = useState(0);
18 const [message, setMessage] = useState("");
19
20 useDidUpdate(() => {
21 setMessage(`The count was updated to ${count}`);
22 }, [count]);
23
24 return (
25 <Card className="relative max-w-md w-full">
26 <CardHeader>
27 <CardTitle>useDidUpdate</CardTitle>
28 <CardDescription>
29 This example uses the <code>useDidUpdate</code> hook to execute a
30 function when the count state is updated.
31 </CardDescription>
32 </CardHeader>
33 <CardContent className="space-y-4">
34 <div className="flex flex-col items-center gap-4">
35 <p className="text-2xl font-bold">{count}</p>
36 <Button onClick={() => setCount((c) => c + 1)}>Increment</Button>
37 <p className="text-sm text-muted-foreground mt-2">{message}</p>
38 </div>
39 </CardContent>
40 </Card>
41 );
42}
43
Install
npx wkkkis-hooks add use-did-update
Options
Name | Type | Default | Description |
---|---|---|---|
callback | void function | () => {} | The function to execute when the component is unmounted. |
deps | DependencyList | [] | The dependencies to watch for changes. |
Update-Only Execution
- The callback is executed only when the dependencies change after the initial mount.
- The callback is not called on the initial mount.
Dependency Handling
- The deps array works like in useEffect : the callback runs when any dependency changes.
- If deps is omitted, the effect will run after every update (except the first mount).
Cleanup
- The hook does not provide a built-in cleanup for the callback itself, but you can return a cleanup function from your callback just like in useEffect .
Best Practices & Caveats
- The hook is client-side only; on the server, it does not run.
- Use for side effects that should only run on updates, not on mount (e.g., reacting to prop or state changes).
- If you need to run logic both on mount and update, use useEffect instead.
Files in this hook
Source | Destination |
---|---|
files/use-did-update.ts | src/hooks/use-did-update.ts |