1.0.1 • Published 5 years ago

use-lazy-hooks v1.0.1

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

Use-lazy-hooks

React hook for resource lazy loading.

Installation

npm install --save use-lazy-hooks

Documentation

The useLazy hook returns an boolean value indicating whether the element is in the specific area or not.

  1. Example
  2. Options

Example

Mostly, we'll need an image to be lazy to save the bandwidth and improve the performance. Let's create an image component with use-lazy hook.

  1. create a ref representing the image dom element that will be mounted.

  2. call the use useLazy hook with the ref object.

Both useRef and React.createRef are the same.

import React, { useRef } from 'react'
import useLazy from 'use-lazy'

function Img(props) {
  const ref = useRef(null)
  const isInSight = useLazy(ref)

  return <img {...props} ref={ref} src={isInSight ? props.src : ''} />
}

Congratulations, you've created a img component that support lazy loading !

Options

  1. ref

    Created by useRef or React.createRef.

  2. coordinate

    The specific area in which the hook returns true. If ignored, the viewport will be the default area. Only right & bottom prop are supported so far !

    interface ICoordinate {
      top?: number,
      right?: number,
      bottom?: number,
      left?: number,
    }
  3. throttle

    The handler for scroll/resize throttle. If ignored, the below debounce handler will be used.

    const debounce = (fn: Function, ctx?: Object, delay: number = 500): EventListener => {
      let timer: number;
      let self: Object = ctx || this;
    
      return (): void => {
        if (timer) clearTimeout(timer);
    
        timer = setTimeout((): void => {
          fn.call(self);
        }, delay);
      }
    }