useHooks is currently down!
useHooks
Hooks

useScroll

Usage

Easy to use, no configuration required.

app/page.tsx
import { useScroll } from "@pyr33x/hooks";
 
export const App = () => {
  const { position, scrollTo } = useScroll();
 
  return (
    <div>
      <p>x: {position.x}</p>
      <p>y: {position.y}</p>
      <button onClick={() => scrollTo({ top: 0, behavior: "smooth" })}>
        Scroll to top
      </button>
    </div>
  );
};

Hook

You can copy & paste the hook below and make it ready to use.

useClient.ts
import { useState, useLayoutEffect } from "react";
 
export const useScroll = () => {
  const [position, setPosition] = useState({
    x: 0,
    y: 0,
  });
 
  const handleScroll = () => {
    setPosition({
      x: window.scrollX,
      y: window.scrollY,
    });
  };
 
  useLayoutEffect(() => {
    window.addEventListener("scroll", handleScroll);
 
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);
 
  return { position, scrollTo: window.scrollTo };
};

On this page