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
refto the element that hasposition: 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:
sidepicks the edge (top,bottom,leftorright) andoffsetis the sticky distance from it, for exampleoffset: 64fortop: 64px. - Scroll containers: pass the scrollable element as
rootwhen the element sticks inside it rather than to the page. - Efficient: it re-renders only when
isStuckchanges, not while you scroll. - Pause:
enabled: falsedisconnects the observer andisStuckisfalseuntil it is turned back on. - SSR-safe:
isStuckisfalseon the server, on the first render, and whereverIntersectionObserveris unavailable. - Cleanup: the observer is disconnected and the marker is removed on
unmount, when the element or an option changes, and when
enabledbecomesfalse.
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?
Optional side, offset, root and enabled settings. See UseIsStuckOptions.
Returns
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.