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.
- 1. Rendering
Creating portals with custom usePortal hook
We will change the screens with useStepper hook
Manage components appearance with useToggle hook
Removing server warnings for useLayoutEffect with custom hook
- 2. Forms
- 3. Events
Read the scroll metadata and direction with useScroll hook
Using clipboard with useClipboard hook
Detect outside click with the useClickOutside hook
Deep dive into useIntersectionObserver hook
Element size measurement with useElementSize hook
- 4. Guards
- 5. Interactions