DOM Hooks
useElementSize, useResizeObserver, useIntersection, useClickOutside, useMergedRef, useScrollLock, useWindowResize, useWindowScroll.
useElementSize
Tracks an element's dimensions using ResizeObserver. Returns a callback ref and the current size.
import { useElementSize } from '@vitus-labs/hooks'
function ResizablePanel() {
const [ref, { width, height }] = useElementSize()
return (
<div ref={ref} style={{ resize: 'both', overflow: 'auto' }}>
Width: {width}px, Height: {height}px
</div>
)
}Returns
[(node: Element | null) => void, { width: number; height: number }]
| Index | Type | Description |
|---|---|---|
| 0 | Callback ref | Attach to the element |
| 1 | { width, height } | Current dimensions (initial: { 0, 0 }) |
Reads initial dimensions from getBoundingClientRect() and updates via ResizeObserver. Both reads use the border box (borderBoxSize), so the initial and observed values are consistent. Updates with unchanged dimensions do not re-render.
SSR safe — gracefully returns { 0, 0 } when ResizeObserver is unavailable.
useResizeObserver
Returns the latest contentRect of the element held by a ref. Lower-level than useElementSize — it exposes the full DOMRectReadOnly (including top/left) and takes an object ref instead of returning a callback ref.
import { useResizeObserver } from '@vitus-labs/hooks'
function Measured() {
const ref = useRef<HTMLDivElement>(null)
const rect = useResizeObserver(ref)
return <div ref={ref}>width: {rect?.width ?? 0}px</div>
}Parameters
| Parameter | Type | Description |
|---|---|---|
ref | RefObject<HTMLElement | null> | Ref to the element to observe |
Returns
DOMRectReadOnly | null — null until the first observation (and when ResizeObserver is unavailable).
The ref's element is tracked after every commit, so an element that mounts later ({open && <div ref={ref} />}) or is swapped is still observed.
useIntersection
Observes element intersection with viewport or a root element using IntersectionObserver.
import { useIntersection } from '@vitus-labs/hooks'
function LazyImage({ src, alt }) {
const [ref, entry] = useIntersection({ threshold: 0.1 })
return (
<div ref={ref}>
{entry?.isIntersecting ? (
<img src={src} alt={alt} />
) : (
<div style={{ height: 200, background: '#eee' }} />
)}
</div>
)
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
threshold | number | number[] | 0 | Visibility percentage (0-1) |
rootMargin | string | '0px' | Margin around root |
root | Element | null | null | Root element (null = viewport) |
Returns
[(node: Element | null) => void, IntersectionObserverEntry | null]
The entry object contains: isIntersecting, intersectionRatio, boundingClientRect, intersectionRect, rootBounds, target, time.
SSR safe — returns null entry when IntersectionObserver is unavailable.
useClickOutside
Detects clicks and touch events outside a referenced element. Useful for closing dropdowns, modals, or popovers.
import { useClickOutside } from '@vitus-labs/hooks'
function Dropdown({ onClose }) {
const ref = useRef<HTMLDivElement>(null)
useClickOutside(ref, onClose)
return (
<div ref={ref}>
Dropdown content — clicking outside closes it
</div>
)
}Parameters
| Parameter | Type | Description |
|---|---|---|
ref | { current: Element | null } | Ref to the element |
handler | (event: Event) => void | Callback when click/touch occurs outside |
Listens to pointerdown on document (covering mouse, touch and pen with a single event, so the handler fires once per tap), falling back to mousedown + touchstart where pointer events are unavailable. Uses event.composedPath() when available, so targets removed from the DOM during the event and shadow-DOM retargeting are handled correctly. Always calls the latest handler.
useMergedRef
Merges multiple refs (callback or object refs) into a single stable callback ref.
import { useMergedRef } from '@vitus-labs/hooks'
import { forwardRef, useRef } from 'react'
const Input = forwardRef((props, forwardedRef) => {
const localRef = useRef<HTMLInputElement>(null)
const mergedRef = useMergedRef(forwardedRef, localRef)
return <input ref={mergedRef} {...props} />
})Parameters
| Parameter | Type | Description |
|---|---|---|
...refs | (Ref<T> | undefined)[] | Any number of refs |
Returns
(node: T | null) => void — merged callback ref.
Handles undefined refs gracefully. Supports mixing callback refs and object refs, and honours React 19 ref cleanups: when a callback ref returns a cleanup function, it is called on detach instead of calling the ref with null.
useScrollLock
Locks page scroll by setting overflow: hidden on document.body. Restores the original value on disable or unmount. Locks are reference-counted, so several concurrent locks (e.g. stacked modals) don't clobber each other — the original overflow is restored only when the last one releases.
import { useScrollLock } from '@vitus-labs/hooks'
function Modal({ isOpen, children }) {
useScrollLock(isOpen)
if (!isOpen) return null
return <div className="modal">{children}</div>
}Parameters
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | Lock scroll when true |
useWindowResize
Tracks browser viewport dimensions with configurable throttling.
import { useWindowResize } from '@vitus-labs/hooks'
function ResponsiveLayout() {
const { width, height } = useWindowResize({ throttleDelay: 200 })
return (
<div>
{width > 768 ? <DesktopLayout /> : <MobileLayout />}
<footer>Viewport: {width} x {height}</footer>
</div>
)
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
params.throttleDelay | number | 200 | Throttle delay (ms) |
params.onChange | ({ width, height }) => void | — | Callback on resize |
initialValues | { width?, height? } | { width: 0, height: 0 } | Initial values before mount (the real viewport is read in an effect after mount) |
Returns
{ width: number; height: number } — current viewport dimensions. Ticks that resolve to unchanged dimensions do not re-render, and onChange only fires on real changes.
On React Native the hook reads Dimensions.get('window') and subscribes to its change event; throttleDelay is accepted for API compatibility but ignored.
useWindowScroll
Tracks the window scroll position. Updates are throttled to one per animation frame and the scroll listener is passive.
import { useWindowScroll } from '@vitus-labs/hooks'
function BackToTop() {
const { y } = useWindowScroll()
if (y < 400) return null
return <button onClick={() => window.scrollTo({ top: 0 })}>Back to top</button>
}Returns
{ x: number; y: number } — { x: 0, y: 0 } on the server and until mount.
Last updated on