intersection observer and react-intersection-observer



~2 min read


223 words

I was reviewing a project recently that made use of the react-intersection-observer library and was fascinated by the simplicity of the API - particularly the hooks version.1

You pass in intersection options and it returns:

  • a ref which can be passed along to the component for tracking purposes
  • inView a boolean that evaluates whether the component is or is not in view
  • entry, which is the IntersectionObserverEntry, which “describes the intersection between the target element and its root container at a specific moment of transition.”2

A simple use case (the repo has better examples) to see how it can be used:

import React from "react"
import { useInView } from "react-intersection-observer"

const Container = (props) => {
  const { scrollDirection } = props

  const [ref, inView] = useInView({
      "-" +
        window.innerHeight * (scrollDirection === "scrollingDown" ? 0.25 : 0.4),
      ) +

  return <div ref={ref}>{inView && props.children}</div>

export default React.memo(Container)

In this case, we didn’t need access to entry, but instead toggle the children on/off based on whether or not the containing div is inView (which in this case means either 25% or 40% of it is visible depending on the direction of scroll).


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!