Skip to content
Sensors

useWindowScroll

Tracks the window scroll position, direction, arrived state, and scrolling status as reactive Observable values. A convenience wrapper around useScroll(window).

x: 0y: 0idle
topbottomleftright

Scroll the page to see the values update in real time.

import {
const useWindowScroll: (options?: DeepMaybeObservable<UseWindowScrollOptions>) => UseWindowScrollReturn
useWindowScroll
} from "@usels/web";
function
function Component(): JSX.Element
Component
() {
const {
const x$: any
x$
,
const y$: any
y$
,
const arrivedState$: any
arrivedState$
} =
function useWindowScroll(options?: DeepMaybeObservable<UseWindowScrollOptions>): UseWindowScrollReturn
useWindowScroll
();
return (
<
JSX.IntrinsicElements.p: DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
p
>
scrollX: {
const x$: any
x$
.
any
get
()}, scrollY: {
const y$: any
y$
.
any
get
()}
{
const arrivedState$: any
arrivedState$
.
any
bottom
.
any
get
() && " — reached bottom"}
</
JSX.IntrinsicElements.p: DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>
p
>
);
}
// @noErrors
import { useWindowScroll } from "@usels/core";
function BackToTop() {
const { arrivedState } = useWindowScroll();
return !arrivedState.top.get() ? (
<button onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>↑ Back to top</button>
) : null;
}
const { directions } = useWindowScroll();
// directions.bottom.get() → true while scrolling down
// directions.top.get() → true while scrolling up
import { useObserveEffect } from "@usels/core";
const { arrivedState } = useWindowScroll({ offset: { bottom: 200 } });
useObserveEffect(arrivedState.bottom, (e) => {
if (e.value) fetchNextPage();
});
const { isScrolling } = useWindowScroll({
idle: 300,
onStop: () => saveScrollPosition(),
});
const { y } = useWindowScroll({ throttle: 100 });

SSR-safe. When window is not available (SSR), useWindowScroll passes null to useScroll, so all observables hold initial values (x: 0, y: 0, isScrolling: false) and no event listener is registered.

See useScroll for the full API reference including all options.

ParameterTypeDescription
optionsUseScrollOptions (optional)-
OptionTypeDefaultDescription
throttlenumber--
idlenumber--
onScroll((e: Event) => void)--
onStop(() => void)--
onError((error: unknown) => void)--
offset{ left?: number | undefined; right?: number | undefined; top?: number | undefined; bottom?: number | undefined; }--
behaviorScrollBehavior--
eventListenerOptionsAddEventListenerOptions--
windowWindowSource--

UseScrollReturn

NameTypeDescription
x$ObservablePrimitive<number>-
y$ObservablePrimitive<number>-
isScrolling$ObservableBoolean<boolean>-
arrivedState$Observable<ArrivedState>-
directions$Observable<ScrollDirections>-
measure() => void-

View on GitHub