@mks2508/mks-ui
Hooks

useAutoHeight

Hook that tracks element height changes via ResizeObserver for smooth animated transitions.

useAutoHeight

A hook that uses ResizeObserver to track an element's content height, enabling smooth animated height transitions when content changes dynamically.

Import

import { useAutoHeight } from '@mks2508/mks-ui/react';

Basic Usage

function ExpandableContent() {
  const [expanded, setExpanded] = useState(false);
  const { ref, height } = useAutoHeight();

  return (
    <div
      style={{ height, overflow: 'hidden', transition: 'height 0.3s ease' }}
    >
      <div ref={ref}>
        <p>Always visible content</p>
        {expanded && <p>Additional content that changes height</p>}
      </div>
    </div>
    <Button onClick={() => setExpanded(!expanded)}>Toggle</Button>
  );
}

How It Works

  1. Attach the returned ref to the element whose height you want to track
  2. The hook uses ResizeObserver to monitor size changes
  3. The height value updates whenever the element resizes
  4. Apply height to a wrapper element with CSS transitions for smooth animation

API Reference

Parameters

None.

Return Value

PropertyTypeDescription
refRefCallback<HTMLElement>Attach to the content element
heightnumber | 'auto'Current measured height in pixels