Skip to Content
ohooks

useElementRef

Provides a callback ref and reactive state for the mounted DOM element so effects re-run when the node attaches or detaches.

Loading preview...

The useElementRef hook returns a [ref, element] tuple where ref is a stable callback ref and element is the reactive DOM node state (T | null), ensuring effects and hooks re-run whenever a conditionally rendered element mounts or unmounts.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useElementRef.json

Usage

Examples

Observing a Conditionally Rendered Element

Unlike useRef, useElementRef triggers a re-render when the node attaches so dependent useEffect hooks always receive the live element.

Composing with Other DOM Hooks

Pass element directly to hooks or APIs that accept Element | null so subscriptions attach as soon as the node mounts.