Article thumbnail

🔰 Deep dive into useIntersectionObserver hook



We take a look at how to use the native IntersectionObserver API and we'll implement useIntersectionObserver hook.

The use cases for intersection observer

Let's say you have a great homepage with fancy looking animation - you're animating the black hole inside canvas. It's good to animate it only when users actually see it. So you could detect whether the user is seeing the section with the animation and based on that, turn it on or off.


Note how the animation stops when scrolling

The browser have a dedicated API for that - IntersectionObserver. When writing in React, it's a good idea to create a proper hook to handle such logic for your own convenience and the ability to use it in every component.

On this repository you have the final result.

Other use cases for useIntersectionObserver

  • Enabling/disabling animations
  • Showing/hiding an element on the UI
  • Loading code dynamically

How to use useIntersectionObserver hook?

This is how we'll use our useIntersectionObserver hook.


Let's implement useIntersectionObserver

First, let's create interfaces. They will define what our hook will accept and what will return.


Now it's time to implement the useIntersectionObserver hook itself. We have interfaces so we know how it should more or less work.


Hook cannot be used on the server side - so we blocked this option at the very beginning.

In addition, if the native IntersectionObserver API is not supported then our code will not work either. So we logged an error for developers.

Next, we created an IntersectionObserver object, we passed a callback and a configuration object.

Testing useIntersectionObserver hook mechanisms

We need to add tests that allow us to do refactors later.


Full example to play with

Repository with the useIntersectionObserver hook implementation.

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.


Add your honest opinion about this article and help us improve the content.

created: 20-03-2023
updated: 20-03-2023