Use Page Offset

React hook for tracking the offset of the browser window

Use Page Offset is a react hook for tracking the Y offset of a browser window

Current page Y offset (0px)

Installation

npm install use-page-offset

Usage

import React from "react"
import { usePageOffset } from "use-page-offset"

const App = () => {
  const offset = usePageOffset()

  return (
    <div>Page offset {offset}</div>
  )
}

export default App

Parallax Demo

This demo below is a basic example of creating a parallax background image using Tailwind CSS. Its what I'm using on this site at the top. You can see the background image moving at a slower speed to achieve that effect.

import { usePageOffset } from "use-page-offset"

const App = () => {
  const offset = usePageOffset()
  const parallaxSpeed = 3
  return (
    <div className="relative py-64 bg-red-500 overflow-hidden">
    <div
      className="absolute top-0 left-0 w-full h-full object-cover z-10"
      style={{
        transform: 'translate(0px, ${offset / parallaxSpeed}px)',
        backgroundImage: 'url("https://via.placeholder.com/1200x400")',
      }}
    ></div>
    <div className="text-center relative z-20">
      <h1 className="text-5xl font-bold pb-4 text-blueGray-800">
        Text Overlay
      </h1>
    </div>
  </div>
  )
}

export default App

How does this work?

Use Page Offset is a super simple react hook that tracks the pageYOffset of the browser window so you can easily build in effects like parallax & scroll effects.

View the repo at https://github.com/garrettbland/use-page-offset.