Skip to main content

Function: useIsStuck()

useIsStuck<T>(options?): UseIsStuckResult<T>

Defined in: use-is-stuck.ts:181

Tells whether a position: sticky element is currently stuck, so you can give sticky headers, toolbars and action bars a shadow, a border or a different background only while they are pinned.

It uses an IntersectionObserver and no scroll listener, so it does no work on scroll events. CSS cannot tell you where a sticky element would be without sticking, so the hook inserts a hidden zero-size marker (a sentinel) next to the element at that natural position and watches it leave the scroll area. The marker has no size, so it takes no space in a normal block layout.

  • Usage: attach the returned ref to the element that has position: sticky. It is a callback ref, so it also works when the element mounts later, is rendered conditionally, or is swapped for another one.
  • Sides: side picks the edge (top, bottom, left or right) and offset is the sticky distance from it, for example offset: 64 for top: 64px.
  • Scroll containers: pass the scrollable element as root when the element sticks inside it rather than to the page.
  • Efficient: it re-renders only when isStuck changes, not while you scroll.
  • Pause: enabled: false disconnects the observer and isStuck is false until it is turned back on.
  • SSR-safe: isStuck is false on the server, on the first render, and wherever IntersectionObserver is unavailable.
  • Cleanup: the observer is disconnected and the marker is removed on unmount, when the element or an option changes, and when enabled becomes false.

Because the marker is a real child of the element's parent, a flex or grid parent treats it as one more item, which a gap or an explicit grid placement can notice. For left and right the element should be in a flex row, where the marker sits right next to it.

Type Parameters​

T​

T extends Element = HTMLElement

The type of the sticky element. Defaults to HTMLElement.

Parameters​

options?​

UseIsStuckOptions

Optional side, offset, root and enabled settings. See UseIsStuckOptions.

Returns​

UseIsStuckResult<T>

Whether the element isStuck, and the ref to attach to it.

Examples​

// Add a shadow to a sticky header while it is pinned to the top
const { ref, isStuck } = useIsStuck<HTMLElement>();

return (
<header
ref={ref}
style={{
position: "sticky",
top: 0,
boxShadow: isStuck ? "0 2px 8px rgba(0, 0, 0, 0.2)" : "none",
}}
>
Title
</header>
);
// A bottom action bar, and a header that sticks 64px from the top
const bar = useIsStuck<HTMLDivElement>({ side: "bottom" });
const header = useIsStuck<HTMLDivElement>({ offset: 64 });
// A sticky table header inside a scrollable container
const [scroller, setScroller] = useState<HTMLDivElement | null>(null);
const { ref, isStuck } = useIsStuck<HTMLTableRowElement>({ root: scroller });

For a live, editable example, see the useIsStuck docs page.

See​