Skip to content

useIntersectionObserver

Handle the IntersectionObserver using this hook.

Parameters

  1. the IntersectionObserver callback function.
  2. the IntersectionObserver options, as well as the ref object of the target element.

INFO

the root option of the observer is replaced by container which is a function that returns the root element in this hook.

Return Values

NameTypeDescription
refRefObjectthe target element reference.
observerRefObjectthe IntersectionObserver object reference.

Example Usage

TIP

Just use useInView if you want to check if an element is intersecting or not.

tsx
import { useIntersectionObserver } from 'react-pre-hooks';

export default function Example() {
  const { ref } = useIntersectionObserver(
    entries => {
      const p = document.querySelector('p')!;

      if (entries[0].isIntersecting) p.textContent = "it's in the view!";
      else p.textContent = "it's not in the view!";
    },
    { threshold: 0.8 }
  );

  return (
    <main>
      <p>Scroll down..</p>
      <div ref={ref}></div>
    </main>
  );
}
import { useIntersectionObserver } from 'react-pre-hooks';

export default function Example() {
  const { ref } = useIntersectionObserver(
    entries => {
      const p = document.querySelector('p')!;

      if (entries[0].isIntersecting) p.textContent = "it's in the view!";
      else p.textContent = "it's not in the view!";
    },
    { threshold: 0.8 }
  );

  return (
    <main>
      <p>Scroll down..</p>
      <div ref={ref}></div>
    </main>
  );
}

Released under the MIT License.