useScrollPosition
This hook allows you to track the current document scroll position by monitoring window.scrollX and window.scrollY. When the user scrolls, the hook will automatically update the returned x and y values.
Installation
-
Make sure you have
@ridgehkr/usefulinstalled in your application. If not, you can get started by following the installation instructions. -
Import
useScrollPositioninto your component.
import { useScrollPosition } from '@ridgehkr/useful'Usage
The useWindowSize hook doesn't take any parameters. It returns an object with the current width and height in pixels of the browser window. The following is a basic example that displays the current window size:
ScrollPosition.tsx
import { useScrollPosition } from '@ridgehkr/useful'
function ScrollPosition() {
const { x, y } = useScrollPosition()
return (
<div
style={{
minHeight: '150vh',
textAlign: 'center',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
minWidth: '150vw',
backgroundColor: '#dedede',
}}
>
<div>
<p>
Scroll X: <strong>{x}</strong>
</p>
<p>
Scroll Y: <strong>{y}</strong>
</p>
<p>Scroll the window to see the X and Y values change.</p>
</div>
</div>
)
}API Reference
Hook Signature
useScrollPosition(): ScrollPositionParameters
useScrollPosition does not accept any parameters.
Return Value
The hook returns a ScrollPosition object with the following properties:
| Property | Type | Description |
|---|---|---|
x | number | The number of pixels that the document is currently scrolled horizontally |
y | number | The number of pixels that the document is currently scrolled vertically |
Last updated on