以前作ったカスタムフックが複雑すぎたのでシンプル版を作りました。
useScroll.tsx
import { useEffect, useState } from 'react'; export default function useScroll() { const [ scrollTop, setScrollTop ] = useState(0); const [ scrollLeft, setScrollLeft] = useState(0); useEffect(() => { window.removeEventListener('scroll', handleScroll); window.addEventListener('scroll', handleScroll, { passive: true }); handleScroll(); return () => { window.removeEventListener('scroll', handleScroll); } }, []); function handleScroll() { setScrollTop(window.scrollY); setScrollLeft(window.scrollX); } return { scrollLeft, scrollTop }; }
useResize.tsx
import { useEffect, useState } from 'react'; export default function useResize() { const [ windowWidth, setWindowWidth ] = useState(0); const [ windowHeight, setWindowHeight ] = useState(0); useEffect(() => { window.removeEventListener('resize', handleResize); window.addEventListener('resize', handleResize, { passive: true }); handleResize(); return () => { window.removeEventListener('resize', handleResize); } }, []); function handleResize() { setWindowWidth(window.innerWidth); setWindowHeight(window.innerHeight); } return { windowWidth, windowHeight }; }
使い方
import useResize from '../hooks/useResize'; import useScroll from '../hooks/useScroll'; import { useEffect } from 'react'; export default function IndexPage() { const { windowWidth, windowHeight } = useResize(); const { scrollLeft, scrollTop } = useScroll(); return ( <div> <p>width: { windowWidth }px</p> <p>height: { windowHeight }px</p> <p>scrollLeft: { scrollLeft }px</p> <p>scrollTop: { scrollTop }px</p> </div> ); }
こんな感じで使います。