[React] scroll 값 참조

bunny.log·2022년 7월 26일
import React, { useState, useEffect } from 'react';

const ScrollComponent = () => {
  const [scrollY, setScrollY] = useState(0);

  const handleFollow = () => {
    setScrollY(window.pageYOffset);
  };

  useEffect(() => {
    console.log("ScrollY is ", scrollY);
  }, [scrollY]);

  useEffect(() => {
    const watchScroll = () => {
      window.addEventListener('scroll', handleFollow);
    };

    watchScroll();

    return () => {
      window.removeEventListener('scroll', handleFollow);
    };
  }, []); // useEffect의 두 번째 인자로 빈 배열을 전달하여 최초 렌더링 시에만 실행되도록 설정

  return (
    // 컴포넌트의 나머지 렌더링 로직을 추가할 수 있습니다.
  );
};

export default ScrollComponent;
profile
더 많은 유익한 내용은 ->> https://github.com/nam-yeun-hwa

0개의 댓글