Deep dive into useIntersectionObserver hook

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.
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.
Usage
This is how we will use our
useIntersectionObserver
hook.
// The visible flag will change if the div will have 40% visibility. const { visible, ref } = useIntersectionObserver<HTMLDivElement>({ treshhold: 0.4 }); return ( <> {/*We pass ref to element we want to observe.*/} <div ref={ref} style={{ minHeight: '100vh' }}> Your main homepage section. </div> <div style={{ minHeight: '100vh' }}> Other home page content. </div> <div>{visible ? 'Main homepage section is visible' : ''}</div> </> )
Use cases
Implementation
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.
Tests
We need to add tests that allow us to do refactors later.
Repository
with the
useIntersectionObserver
hook.
Now you know how to track any element on the interface and respect the resources of the browser.
If you enjoyed it, be sure to visit us on
Linkedin
where we regularly upload content from programming.