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

ParamTypeRequiredDefaultDescription
throttlerThrottleWrapperfalse-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.

PropTypeDescription
xnumberThe current coordinate on the x-axis (window.pageXOffset)
ynumberThe current coordinate on the y-axis (window.pageYOffset)