useIntersection

Overview

The useIntersection hook allows you to lazy load any resource when it is near to the viewport. It uses the IntersectionObserver under the hood.

Import

The useIntersection hook can be imported directly from the frontend-ui package, which is pre-installed in your Shogun Frontend store.

import { useIntersection } from 'frontend-ui'

Usage

Below is an example of how to use the useIntersection hook:

import React from 'react'
import { useIntersection } from 'frontend-ui'

const MyComponent = () => {
  const elementRef = React.useRef(null)

  const [visible, setVisible] = useIntersection(elementRef, {
    // some condition
    disabled: loading === 'eager',
    rootMargin: '1250px',
  })

  return (
    <React.Fragment>
      <button onClick={() => setVisible(true)}>
        Load below the fold content
      </button>
      {/* somewhere below the fold */}
      <div ref={elementRef}>
        {visible ? 'On the viewport' : 'hidden'}
      </div>
    </React.Fragment>
  )
}

export default MyComponent

Configuration

The useIntersection hook accepts two parameters; elementRef and an options object with rootMargin and disabled.

nametypedefault valuedescription
elementRefReact.RefThe element reference.
optionsobjectAn object of configuration options. It accepts two keys: rootMargin and disabled.
options.rootMarginstring200pxMargin around the root. This is the distance from the viewport when the content should start loading.
options.disabledbooleanfalseTo disable IntersectionObserver and load the resource instantly.

Return values

The useIntersection hook will return the following values:

nametypedescription
visiblebooleanDetermine whether the element is visible.
setVisible() => boleanSetter to control the visible property.

Further resources