Skip to main content

useWindowScroll

A React hook that tracks the current window scroll position and provides helper functions to programmatically scroll to specific positions.

npm install @plenty-hooks/use-window-scroll

Showcase

import useWindowScroll from '@plenty-hooks/use-window-scroll';

function ScrollTrackerComponent() {
const [scroll, { scrollTo, scrollToX, scrollToY, scrollToTop }] = useWindowScroll();

return (
<div>
<div
style={{
position: 'fixed',
top: 0,
right: 0,
padding: '1rem',
background: 'white',
}}
>
<p>X: {scroll.x}px</p>
<p>Y: {scroll.y}px</p>
</div>

<button onClick={() => scrollToTop()}>Scroll to Top</button>

<button onClick={() => scrollTo(0, 500)}>
Scroll to 500px
</button>

<button onClick={() => scrollTo(100, 1000)}>
Scroll to Custom Position
</button>

<button onClick={() => scrollToY(800)}>
Scroll Vertically to 800px
</button>

<button onClick={() => scrollToX(200)}>
Scroll Horizontally to 200px
</button>
</div>
);
}

Global Configuration

You can configure default options globally:

import { configUseWindowScroll } from '@plenty-hooks/use-window-scroll';

// Configure once in your app entry point
configUseWindowScroll({
behavior: 'smooth',
passive: true,
capture: false,
});

API

useWindowScroll(options?: Options)

Returns the current scroll position and provides scroll helper functions. The hook automatically tracks scroll position updates.

Parameters

  • options (optional): Configuration object with the following properties:
    • behavior?: ScrollBehavior - Default scroll behavior for scrollTo and scrollToTop functions (default: undefined, which uses browser default)
    • capture?: boolean - Use capture phase for scroll event listener (default: false)
    • passive?: boolean - Use passive event listener for better scroll performance (default: false)

Returns

A tuple [scroll, actions] containing:

  • scroll: { x: number, y: number } - Current scroll position
    • x: number - The current horizontal scroll position in pixels
    • y: number - The current vertical scroll position in pixels
  • actions: object - Object containing scroll helper functions:
    • scrollTo: (x: number, y: number) => void - Scrolls to a specific X and Y coordinate
    • scrollToX: (x: number) => void - Scrolls horizontally to the specified X coordinate (keeps current Y)
    • scrollToY: (y: number) => void - Scrolls vertically to the specified Y coordinate (keeps current X)
    • scrollToTop: () => void - Scrolls to the top of the page (Y=0)

configUseWindowScroll(options: Options)

Configures global default options for the useWindowScroll hook.

Parameters

  • options: Options - Configuration object with properties matching the hook options

Server-Side Rendering (SSR)

During server-side rendering the hook returns { x: 0, y: 0 } for the scroll position.