useScrollPosition
Keep track of window scroll position while the user scrolls. Optionally you can
pass in a throttle wrapper to throttle the update calls (e.g. using
lodash.throttle or
window.requestAnimationFrame
).
Usage
import React from 'react';import { useScrollPosition } from '@fransvilhelm/hooks';const FadeInOnPosition = ({ breakpoint, children }) => {const { y } = useScrollPosition((fn) => () =>window.requestAnimationFrame(fn),);const fadeIn = y >= breakpoint;return (<Animation type="fadeIn" enable={fadeIn}>{children}</Animation>);};
Example
There will not be that much difference. But if other heavy computations are made in parallell the throttler can be useful.
Without any throttling function: x: 0px / y: 0px
Parameters
useScrollPosition
accepts one optional parameter – a throttling function
Param | Type | Required | Default | Description |
---|---|---|---|---|
throttler | ThrottleWrapper | false | - | The throttle function should accept a callback as initial argument and the return another function that when called will throttle the update |
Returns
useScrollPosition
returns an object with the current coordinates for the
scroll position.
Prop | Type | Description |
---|---|---|
x | number | The current coordinate on the x-axis (window.pageXOffset ) |
y | number | The current coordinate on the y-axis (window.pageYOffset ) |