Today we are gonna explore how to use the intersection observer API in React and see some useful examples, you can find the code in the following repository, let's begin.
Mozilla web documentation describes the intersection observer API as:
lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. This way, sites no longer need to do anything on the main thread to watch for this kind of element intersection, and the browser is free to optimize the management of intersections as it sees fit.
In plain english, it allows us to detect when certain elements are visible in our viewport, this only happens when the element meets your desired intersection ratio.
As you can see, if we scroll down the page the intersection ratio will be going up until it meets the designed threshold and that's when the callback function is executed.
Initialization
The intersection observer object constructor requires two arguments:
- Callback function
- Options
Just like that we are ready to see some action but first we need to know what each option means, the options argument is an object with the following values:
- root: The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null.
- rootMargin: This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections, the options are similar to those of margin in CSS.
- threshold: Either a single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed, ranges from 0 to 1.0, where 1.0 means every pixel is visible in the viewport.
Using React.js
Now let's see an implementation of the intersection observer API using react.
- Start with a reference to the element we want to observe, use the react hook useRef.
- Create a state variable
isVisible
, we are gonna use it to display a message whenever our box is in the viewport. - Declare a callback function that receives an array of IntersectionObserverEntries as a parameter, inside this function we take the first and only entry and check if is intersecting with the viewport and if it is then we call
setIsVisible
with the value ofentry.isIntersecting
(true/false). - Create the options object with the same values as the image.
- Add the react hook useEffect and create an observer contructor using the callback function and the options we just created before, it's optional in our case but you can return a cleanup function to unobserve our target when the component unmounts.
- Set the useRef variable on the element we want to observe.
- Let's add a background and some properties to our HTML elements
- It's done, simple and easy!
remember this is just a basic implementation and there are many different ways of doing it.
Hooking it up
Let's now implement the same code we just did before but separating all the logic into a new hook called useElementOnScreen
.
- Create a new function called
useElementOnScreen
with the parameter options - Move useRef, useState and the entire useEffect inside our new shiny hook.
- Now the only thing missing in our hook is the return statement, we pass
isVisible
andcontainerRef
as an array. - okay, we are almost there, we just need to call it in our component and see if it works!
- Import the recently created hook file into our component.
- Initialize it with the options object.
- Just like that we are done.
Congratulations we have successfully used the intersection observer API and we even made a hook for it!
Final words
Thanks for reading this, Hopefully it helped someone getting started with the IO API using react, stay safe ❤️!
Top comments (25)
Great job! I have one question: would this work the same between components? For example: parent component that maps inside a list of , I asume that the IO will be implemented in the parent, but do I have to create a ref for each item? Sorryif ai didn't explained myself correctly... And thanks for this post
yes, you asumed correctly the parent component needs the IO and what we get there is the entire element's size of the component including the items inside or whatever we want to have there, we dont need to add to each item a ref.
Thanks for reading it!
I had no idea on how to use this properly, thanks for the article.
I think there are couple of things worth pointing out:
That being said, we might as well omit the dependency array altogether, it will have the same effect.
Update:
There's the npm package react-intersection-observer that does the job for you, additionally you got also a component you can wrap around your element to make your code more clean :)
npmjs.com/package/react-intersecti...
Your example is not entirely correct. The containerRef will not trigger the useEffect, and it should not be included in its dependencies. For more details, please refer to this article medium.com/@teh_builder/ref-object...
This helped me tremendously! Tysm!
Thanks for a great article/tutorial - it helped me alot in implementing lazy-loading of content based on visibility in a React project.
In doing so, however, it seems calling observer.unobserve(target) in the cleanup is not enough - react complains about calling setState on unmounted component. calling observer.disconnect() seem to unregister the IntersectionObserver completely and made React stop complaining.
Thank You for great tutorial, very helpful for my gatsby project
I had to create my account on this site just to comment and like this post, congratulations
I just implemented a behavior in my blog header using the Intersection Observer
If you want to see: demenezes.dev
Thank you for that. I'm using your hook in a nextjs portfolio project and it works perfectly.
Nice!