1.0.4 • Published 5 years ago

@tripair/use-scroll v1.0.4

Weekly downloads
48
License
MIT
Repository
github
Last release
5 years ago

use-scroll

use-scroll is a React hook that returns the browser viewport X and Y scroll position. It is highly optimized and using the special technics to avoid unnecessary rerenders!

It uses the default react hooks rendering lifecycle, which allows you to fully control its behavior and prevent unnecessary renders.

Install

yarn add use-scroll

Usage

useScroll(effect, selector, deps, element, wait)
ArgumentsDescription
effectEffect callback.
selectorUse window instead of selector if selector not set.
depsFor effects to fire on selected dependencies change.
elementGet scroll position for a specified element by reference.
waitThe timeout in ms. Good for performance.

The useScroll returns prevPos and currPos.

Examples

Log current scroll position

import { useScroll } from '@n8tb1t/use-scroll-position'
  
useScroll(({ prevPos, currPos }) => {
  console.log(currPos.x)
  console.log(currPos.y)
})

Change state based on scroll position - Inline CSS

import React, { useState } from 'react'
import { useScroll } from 'use-scroll'

const [headerStyle, setHeaderStyle] = useState({
  transition: 'all 200ms ease-in'
})

useScroll(
  ({ prevPos, currPos }) => {
    const isVisible = currPos.y > prevPos.y

    const shouldBeStyle = {
      visibility: isVisible ? 'visible' : 'hidden',
      transition: `all 200ms ${isVisible ? 'ease-in' : 'ease-out'}`,
      transform: isVisible ? 'none' : 'translate(0, -100%)'
    }

    if (JSON.stringify(shouldBeStyle) === JSON.stringify(headerStyle)) return

    setHeaderStyle(shouldBeStyle)
  },
  [headerStyle]
)

const Header = <header style={{ ...headerStyle }} />

Change state based on scroll position - Styled Components

import React, { useState } from 'react'
import { useScroll } from 'use-scroll'

const [hideOnScroll, setHideOnScroll] = useState(true)
  
useScroll(({ prevPos, currPos }) => {
  const isShow = currPos.y > prevPos.y
  if (isShow !== hideOnScroll) setHideOnScroll(isShow)
}, [hideOnScroll])

Get scroll position for custom element

  const [elementPosition, setElementPosition] = useState({ x: 20, y: 150 })
  const elementRef = useRef()
  
    // Element scroll position
  useScroll(
    ({ currPos }) => {
      setElementPosition(currPos)
    }, [], elementRef
  )
1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago