Frontend/React Hook

[React-Hooks] React Hooks - useScroll

갈푸라떼 2022. 7. 13. 16:22

* useScroll

  • 스크롤을 해서 무언가를 지나쳤을때 색상을 바꾸거나 어떤 행동을 하는 Hook이다.

* useScroll 예시코드

import { useEffect, useState } from "react";

const useScroll = () => {
  const [state, setState] = useState({
    x: 0,
    y: 0,
  });
  const onScroll = () => {
    setState({ y: window.scrollY, x: window.scrollX });
  };
  useEffect(() => {
    window.addEventListener("scroll", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
    };
  });
  return state;
};

const App = () => {
  const { y } = useScroll();
  return (
    <div style={{ height: "1000vh" }}>
      <h1 style={{ position: "fixed", color: y > 200 ? "red" : "blue" }}>Hi</h1>
    </div>
  );
};

export default App;