useRetained
Keeps the last non-null value while a dialog animates closed.
For a dialog, sheet or popover that shows whichever record is selected, where closing sets the selection to null. Without it the content empties the moment the exit starts. useRetained(selected) gives open for the overlay, value (the selection, or the last one while the overlay leaves) to render, and onOpenChangeComplete to pass to the overlay so the kept copy is dropped once the exit has finished.
A dialog that keeps its content
- INV-1042
- INV-1041
- INV-1040
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { useRetained } from "@/hooks/use-retained"
const invoices = [
{ number: "INV-1042", project: "Atlas redesign", due: "30 November" },
{ number: "INV-1041", project: "Billing migration", due: "24 November" },
{ number: "INV-1040", project: "Harbor mobile app", due: "15 November" },
]
export default function UseRetainedADialogThatKeepsItsContent() {
// Closing sets the selection to null at once; the dialog still has an exit to play.
const [selected, setSelected] = useState<(typeof invoices)[number] | null>(null)
const invoice = useRetained(selected)
return (
<>
<ul className="flex w-full max-w-xs flex-col gap-2">
{invoices.map((entry) => (
<li key={entry.number} className="flex items-center justify-between gap-2">
<span>{entry.number}</span>
<Button variant="outline" aria-label={`Open ${entry.number}`} onClick={() => setSelected(entry)}>
Open
</Button>
</li>
))}
</ul>
<Dialog
open={invoice.open}
onOpenChange={(open) => !open && setSelected(null)}
onOpenChangeComplete={invoice.onOpenChangeComplete}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{invoice.value?.number}</DialogTitle>
<DialogDescription>
{invoice.value?.project}, due on {invoice.value?.due}.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose render={<Button variant="outline" />}>Close</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
Installation
npx shadcn@latest add @khaeli/use-retainedbunx --bun shadcn@latest add @khaeli/use-retainedInstalls with
Nothing else. This item needs no other Registry item and no npm package.
Keyboard
Esc- Closes the dialog. Its title and text stay as they were until it has left.
Accessible name
- Take the overlay's title from
value, not from the selection, so the dialog keeps its name while it closes.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/use-retained.json