/* Code-Comments */

Intersection Observer and React-Intersection-Observer

October 25, 2019

I was reviewing a project recently that made use of the react-intersection-observer library and was fascinated by the simplicty 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({
    rootMargin:
      '-' +
      String(
        window.innerHeight * (scrollDirection === 'scrollingDown' ? 0.25 : 0.4)
      ) +
      'px',
  })

  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).

Footnotes


Stephen Weiss

Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!