useIntersectionObserver (useIntersectionObserver/index.ts)

react-hookz/web · src/useIntersectionObserver/index.ts · typescript · MIT
ui

Detects when HTML elements enter or leave the viewport for infinite scroll and lazy loading.

// Source: https://github.com/react-hookz/web | License: MIT | Copyright 2021 react-hookz
// Provided via justclaw.it.com; keep this notice with the code.
import type {RefObject} from 'react';
import {useEffect, useState} from 'react';

const DEFAULT_THRESHOLD = [0];
const DEFAULT_ROOT_MARGIN = '0px';

type IntersectionEntryCallback = (entry: IntersectionObserverEntry) => void;

type ObserverEntry = {
	observer: IntersectionObserver;
	observe: (target: Element, callback: IntersectionEntryCallback) => void;
	unobserve: (target: Element, callback: IntersectionEntryCallback) => void;
};

const observers = new Map<Element | Document, Map<string, ObserverEntry>>();

const getObserverEntry = (options: IntersectionObserverInit): ObserverEntry => {
	const root = options.root ?? document;

	let roo

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key