use-scroll-position (use-scroll-position)
Tracks the current scroll position of the page.
v0.1.0
Usage
import { use-scroll-position } from "@/hooks"
1"use client";
2
3import {
4 Card,
5 CardContent,
6 CardDescription,
7 CardFooter,
8 CardHeader,
9 CardTitle,
10} from "@/components/ui/card";
11
12import { useScrollPosition } from "@/components/hooks/use-scroll-position";
13
14export function UseScrollPositionDemo() {
15 const { x, y } = useScrollPosition();
16
17 return (
18 <Card className="relative max-w-md w-full">
19 <CardHeader>
20 <CardTitle>useScrollPosition</CardTitle>
21 <CardDescription>
22 This component uses the <code>useScrollPosition</code> hook to track
23 the page scroll position.
24 </CardDescription>
25 </CardHeader>
26 <CardContent className="space-y-2">
27 <p>Scroll X: {x}px</p>
28 <p>Scroll Y: {y}px</p>
29 </CardContent>
30 <CardFooter>
31 <p className="text-sm text-muted-foreground">
32 Scroll the page to see the values change.
33 </p>
34 </CardFooter>
35 </Card>
36 );
37}
38
Install
npx wkkkis-hooks add use-scroll-position
Options
Name | Type | Default | Description |
---|---|---|---|
onChange? | (x: number, y: number) => void | undefined | A callback function called when the scroll position changes. |
SSR & Initial Values
- The hook checks if it's running in a browser. On the server, it returns 0 for both x and y .
- On mount, the hook initializes the scroll position based on the current window.scrollX and window.scrollY .
Passive Scroll Listener
- The scroll listener is registered with { passive: true } for better performance.
- The listener is cleaned up on unmount to prevent memory leaks.
Files in this hook
Source | Destination |
---|---|
files/use-scroll-position.ts | src/hooks/use-scroll-position.ts |