How To Use an IntersectionObserver in a React Hook

Travis Waith-Mair
Non-Traditional Dev
9 min readMar 22, 2019

--

Photo by chuttersnap on Unsplash

One of the most difficult things on the web is figuring out if an element is visible or where it is in relation to its parent element. Historically, this meant running calculations triggered by a scroll event, which can quickly become a performance liability for your app.

Luckily, a better and much more performant way to do this has been introduced: the Intersection Observer. The Intersection Observer API allows asynchronous checking of the ratio of the intersection of an element with a viewport and will only fire a callback when the predefined threshold(s) are met. This has opened up many user experiences that were difficult to implement in a performant way, such as infinite scrolling, lazy load images, or delaying animations until visible.

Recently, I wanted to explore how one would implement this in a react hook. I ran into many gotchas, but luckily Dan Abramov recently posted a helpful guide to useEffect over at his blog, Overreacted, which helped me immensely in understanding these gotchas and what I needed to do to fix them. So I thought I would summarize what I learned to help you avoid the same mistakes I encountered.

How Does The Intersection Observer API Work?

To get a complete understanding of the Intersection Observer API, I would recommend…

--

--