useAnimatedAutoHeight
Smoothly animate a container's height as its content grows or shrinks.
Powered by
Installation
npx shadcn@latest add @redpanda/use-animated-auto-heightpnpm dlx shadcn@latest add @redpanda/use-animated-auto-heightyarn dlx shadcn@latest add @redpanda/use-animated-auto-heightbunx shadcn@latest add @redpanda/use-animated-auto-heightnubx shadcn@latest add @redpanda/use-animated-auto-heightaube dlx shadcn@latest add @redpanda/use-animated-auto-heightuseAnimatedAutoHeight returns a callback ref. Attach it to an element and, while enabled, the hook watches that element with a ResizeObserver and animates its height between measured sizes whenever the content changes — no fixed pixel values or manual measuring required. It ignores the height echoes it sets itself during an animation, so it won’t fight its own updates.
Because the ref is state-backed, the effect re-runs once the node attaches — which makes it safe to use on elements that mount lazily inside a portal.
Usage
import { useAnimatedAutoHeight } from "@/hooks/use-animated-auto-height";
function ExpandingPanel({ open }: { open: boolean }) {
// `enabled` guards the animation — e.g. disable it while the panel is closed.
const setNode = useAnimatedAutoHeight<HTMLDivElement>(open);
return (
<div ref={setNode} className="overflow-hidden">
{open ? <TallContent /> : null}
</div>
);
}
API
useAnimatedAutoHeight<T>(enabled)
| Parameter | Type | Description |
|---|---|---|
enabled |
boolean |
When false, no observer is attached and the element’s inline height is reset. |
Returns (node: T \| null) => void — a callback ref to attach to the element whose height should animate.