react-use/src/useScroll.ts
Renovate Bot a27f09fd36
chore: refactoring and rearrangement.
More DRY code. Also move non-hooks to separate directories.

BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint`
BREAKING CHANGE: `comps` directory renamed to `component`
2021-01-30 23:30:26 +03:00

51 lines
1004 B
TypeScript

import { RefObject, useEffect } from 'react';
import useRafState from './useRafState';
import { off, on } from './misc/util';
export interface State {
x: number;
y: number;
}
const useScroll = (ref: RefObject<HTMLElement>): State => {
if (process.env.NODE_ENV === 'development') {
if (typeof ref !== 'object' || typeof ref.current === 'undefined') {
console.error('`useScroll` expects a single ref argument.');
}
}
const [state, setState] = useRafState<State>({
x: 0,
y: 0,
});
useEffect(() => {
const handler = () => {
if (ref.current) {
setState({
x: ref.current.scrollLeft,
y: ref.current.scrollTop,
});
}
};
if (ref.current) {
on(ref.current, 'scroll', handler, {
capture: false,
passive: true,
});
}
return () => {
if (ref.current) {
off(ref.current, 'scroll', handler);
}
};
}, [ref]);
return state;
};
export default useScroll;