scroll hook react in typescript

To create a scroll hook in React using TypeScript, you can use the useEffect hook to listen for scroll events and update the state accordingly.

First, let's define the state interface:

index.ts
interface ScrollPosition {
  x: number;
  y: number;
}
55 chars
5 lines

Then, let's define the useScroll hook:

index.ts
import { useState, useEffect } from "react";

export function useScroll(): ScrollPosition {
  const [position, setPosition] = useState<ScrollPosition>({
    x: window.pageXOffset,
    y: window.pageYOffset,
  });

  useEffect(() => {
    const handleScroll = () => {
      setPosition({
        x: window.pageXOffset,
        y: window.pageYOffset,
      });
    };

    window.addEventListener("scroll", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return position;
}
537 chars
26 lines

In this hook, we use useState() to create state for the scroll position and initialize it to the current scroll position using window.pageXOffset and window.pageYOffset.

We then use useEffect() to add a scroll event listener to the window object. The handleScroll() function is called when a scroll event is fired and updates the position state accordingly.

Finally, we return the position state.

You can now use this hook in your components to get the current scroll position:

index.ts
import { useScroll } from "./useScroll";

function MyComponent() {
  const { x, y } = useScroll();

  return (
    <div>
      <p>Horizontal scroll position: {x}</p>
      <p>Vertical scroll position: {y}</p>
    </div>
  );
}
227 chars
13 lines

gistlibby LogSnag