useIntersection
Updated over a week ago

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.

name

type

default value

description

elementRef

React.Ref

options

object

An object of configuration options. It accepts two keys: rootMargin and disabled.

options.rootMargin

string

200px

Margin around the root. This is the distance from the viewport when the content should start loading.

options.disabled

boolean

false

To disable IntersectionObserver and load the resource instantly.

Return values

The useIntersection hook will return the following values:

name

type

description

visible

boolean

Determine whether the element is visible.

setVisible

() => bolean

Setter to control the visible property.

Further resources

Did this answer your question?