Skip to content

useScroll

React hook to track and manipule the scroll position of a web page.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useScroll
sh
npx @novajslabs/cli add useScroll
sh
pnpm dlx @novajslabs/cli add useScroll

Or copy and paste the code into your project:

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 };
};
js
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 };
};

Requirements

React 16.8 or higher

Return values

position

Type: object

Indicates the current scroll position of the window.

position.x

Type: number

The current horizontal scroll position of the window.

position.y

Type: number

The current vertical scroll position of the window.

scrollTo

Type: function

Allows you to scroll to a specified position.

Example

tsx
import { useScroll } from "./hooks/useScroll";

const App = () => {
  const { position, scrollTo } = useScroll();

  return (
    <div
      style={{
        height: window.innerHeight,
        width: window.innerWidth,
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        flexDirection: "column",
      }}
    >
      <p>x: {position.x}</p>
      <p>y: {position.y}</p>
      <button onClick={() => scrollTo({ top: 0, behavior: "smooth" })}>
        Scroll to top
      </button>
    </div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Track the scroll position to make a header sticky when the user scrolls past a certain point
  • Load more content when the user scrolls near the bottom of the page
  • Trigger animations based on the user's scroll position
  • Highlight navigation items based on the section currently in view
  • Show a button that scrolls the user back to the top of the page

Released under the MIT License.