Package 01 · The hook

use-window-scroll-in-element

A React hook that reports how far the window has scrolled through a target element — as pixels and as a 0 → 1 fraction. Scroll down to bind it to a progress bar, a fade-in, and a parallax scene.

fraction.top → width
0%
fraction.top → opacity + translateY
Fade & Rise
fraction.top → parallax translateY
position.top0px
fraction.top0.000
import { useRef } from 'react';
import { useWindowScrollInElement } from 'use-window-scroll-in-element';

function Showcase() {
  const ref = useRef(null);

  // fraction.top goes from 0 -> 1 as the element
  // scrolls through the viewport.
  const { fraction } = useWindowScrollInElement(ref, {
    scrollStartPosition: 'window-bottom',
    scrollEndPosition: 'window-top',
  });

  const p = fraction.top; // 0 .. 1

  return (
    <div ref={ref}>
      {/* progress bar */}
      <div style={{ width: `${p * 100}%` }} />

      {/* fade + rise in */}
      <div style={{
        opacity: p,
        transform: `translateY(${(1 - p) * 40}px)`,
      }} />

      {/* parallax layers */}
      <div style={{ transform: `translateY(${p * -80}px)` }} />
    </div>
  );
}