Intro
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.
Loading
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.
Loading
Let's implement useIntersectionObserver
First, let's create interfaces. They will define what our hook will accept and what will return.
Loading
Now it's time to implement the useIntersectionObserver hook itself. We have interfaces so we know how it should more or less work.
Loading
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.
Loading
Full example to play with
Repository with the useIntersectionObserver hook implementation.
- 1. Rendering
16 minutes
Creating portals with custom usePortal hook
2 m
We will change the screens with useStepper hook
3 m
Manage components appearance with useToggle hook
4 m
Removing server warnings for useLayoutEffect with custom hook
3 m
First interaction detection with useOnInteraction hook
4 m
- 2. Forms
4 minutes
- 3. Events
26 minutes
Read the scroll metadata and direction with useScroll hook
5 m
Using clipboard with useClipboard hook
4 m
Detect outside click with the useClickOutside hook
6 m
Deep dive into useIntersectionObserver hook
4 m
Element size measurement with useElementSize hook
7 m
- 4. Guards
5 minutes
- 5. Interactions
5 minutes
Comments
Add your honest opinion about this article and help us improve the content.