mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
42 lines
874 B
TypeScript
42 lines
874 B
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { isClient } from './util';
|
|
|
|
export interface State {
|
|
x: number;
|
|
y: number;
|
|
}
|
|
|
|
const useWindowScroll = (): State => {
|
|
const frame = useRef(0);
|
|
const [state, setState] = useState<State>({
|
|
x: isClient ? window.scrollX : 0,
|
|
y: isClient ? window.scrollY : 0,
|
|
});
|
|
|
|
useEffect(() => {
|
|
const handler = () => {
|
|
cancelAnimationFrame(frame.current);
|
|
frame.current = requestAnimationFrame(() => {
|
|
setState({
|
|
x: window.scrollX,
|
|
y: window.scrollY,
|
|
});
|
|
});
|
|
};
|
|
|
|
window.addEventListener('scroll', handler, {
|
|
capture: false,
|
|
passive: true,
|
|
});
|
|
|
|
return () => {
|
|
cancelAnimationFrame(frame.current);
|
|
window.removeEventListener('scroll', handler);
|
|
};
|
|
}, []);
|
|
|
|
return state;
|
|
};
|
|
|
|
export default useWindowScroll;
|