useWindowScroll

A custom React hook to track window scroll position and programmatically scroll to specific coordinates.
useWindowScroll(): [
  { x: number; y: number },
  (options: { x?: number; y?: number }) => void
]
Parameters
  • Returns: A tuple containing:
    • scroll: An object with the current scroll position:
      • x: Horizontal scroll position in pixels.
      • y: Vertical scroll position in pixels.
    • scrollTo: A function to scroll the window to specified coordinates.

Example

import { useWindowScroll } from "daily-toolset/hooks";

// Example usage
function ScrollExample() {
  const [{ x, y }, scrollTo] = useWindowScroll();

  return (
    <div>
      <h1>Window Scroll Position</h1>
      <p>Scroll X: {x}</p>
      <p>Scroll Y: {y}</p>
      <button onClick={() => scrollTo({ x: 0, y: 0 })}>
        Scroll to Top
      </button>
      <button onClick={() => scrollTo({ x: 0, y: 500 })}>
        Scroll to Y: 500
      </button>
    </div>
  );
}

Use Cases

  • Tracking the current scroll position for animations or effects.
  • Providing 'scroll to top' or 'scroll to specific section' buttons.
  • Implementing sticky or dynamic UI elements based on scroll position.