Code Monkey home page Code Monkey logo

use-scroll-position's Introduction

use-scroll-position

Node version Node version Node version

Screenshot

use-scroll-position 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.

Demo

Edit use-scroll-position

Install

yarn add @n8tb1t/use-scroll-position

Usage

useScrollPosition(effect,deps, element, useWindow, wait)
Arguments Description
effect Effect callback.
deps For effects to fire on selected dependencies change.
element Get scroll position for a specified element by reference.
useWindow Use window.scroll instead of document.body.getBoundingClientRect() to detect scroll position.
wait The timeout in ms. Good for performance.

The useScrollPosition returns prevPos and currPos.

Examples

Log current scroll position

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

Change state based on scroll position - Inline CSS

import React, { useState } from 'react'
import { useScrollPosition } from '@n8tb1t/use-scroll-position'

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

useScrollPosition(
  ({ 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 { useScrollPosition } from '@n8tb1t/use-scroll-position'

const [hideOnScroll, setHideOnScroll] = useState(true)
  
useScrollPosition(({ 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
  useScrollPosition(
    ({ currPos }) => {
      setElementPosition(currPos)
    }, [], elementRef
  )

Why to use

use-scroll-position returns the scroll position of the browser window, using a modern, stable and performant implementation.

Most of the time scroll listeners do very expensive work, such as querying dom elements, reading height / width and so on. use-scroll-position solves this by using throttling technic to avoid too many reflows (the browser to recalculate everything).

use-scroll-position's People

Contributors

foxmicha avatar maxusha avatar n8tb1t avatar peterjuras avatar rumtraubenuss avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.