Simple Guide to Using Intersection Observer API with ReactJS

Search for a command to run...

No comments yet. Be the first to comment.
React revolves around JavaScript, and as the application expands, certain components may become error-prone, leading to a blank page problem. To tackle this, we should incorporate Error Boundaries. These boundaries will display an alternative UI when...
Every October, the developer community buzzes with Hacktoberfest energy. PRs fly, t-shirts are earned, and GitHub turns green. But here's what nobody talks about: what happens in November? For most contributors, the answer is simple: nothing. The rep...

The debate over AI coding agents is missing the most important factor. It’s not about prompt engineering, it’s about understanding the context window. Developers are divided. One side claims coding agents suck. The other insists you’re just using the...

Learnings from a Research Paper

Lately, I have been working on a feature to capture images from media streams and scale them down to reduce their size. This helps save storage and reduce costs before uploading the images to a storage service. For this, I used Canvas to render the i...

AI helps you do more, but only if you know the basics well enough to tell it what you want.

The Intersection Observer API is a new web tool that helps developers check when an element in the DOM comes into or leaves the viewport. This is very useful for lazy loading images, infinite scrolling, and other important features that need to know when an element is visible to the user.
In this article, we'll learn how to use the Intersection Observer API with React, a popular JavaScript library for building user interfaces. We'll start by briefly covering the basics of the Intersection Observer API and its benefits. Then, we'll look at a practical example of using it with React to animate a component.
The Intersection Observer API is a web tool that lets developers track when an element in the DOM enters or leaves the viewport or a specified parent element. Simply put, it helps us know when an element appears or disappears on the user's screen.
One of the main benefits of using the Intersection Observer API is that it offers a more efficient way to track the visibility of elements in the DOM compared to methods like using scroll or resize event listeners. The Intersection Observer API uses a callback-based approach, which means we can set a function to run when an element's visibility changes, instead of constantly checking visibility on each scroll or resize event.
To use the Intersection Observer API with React, we can make a custom hook that simplifies using the Intersection Observer API. This hook can be used in any React component to check if an element is visible and take action when it appears.
Here is an example of a custom useElementInView hook that uses the Intersection Observer API to check if an element is visible
const useElementInView = (options) => {
const [isInView, setIsInView] = useState(false);
const targetRef = useRef(null);
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
const [entry] = entries;
setIsInView(entry.isIntersecting);
}, options);
if (targetRef.current) {
observer.observe(targetRef.current);
}
return () => {
if (targetRef.current) {
observer.unobserve(targetRef.current);
}
};
}, [options]);
return [targetRef, isInView];
};
This hook creates an IntersectionObserver instance and watches the target element. When the target element becomes visible within the root element, it updates the state with the visibility info.
To use this hook in a React component, you can pass the options to the hook and get the returned ref and visibility info
const MyComponent = () => {
const [targetRef, isInView] = useElementInView({ threshold: 0.5 });
return (
<div ref={targetRef}>
{isInView ? 'Element is in view!' : 'Element is not in view.'}
</div>
);
};
Alright, we have discussed what the Intersection Observer is and how it works. We created a hook called useElementInView, and in the next section, we will use this hook to animate a component.
useElementInView hookWe will create a component that will animate an element when it comes into view, essentially a scroll-to-reveal animation.
import React from 'react';
import useElementInView from './useElementInView';
const AnimatedComponent = () => {
const [targetRef, isInView] = useElementInView({ threshold: 0.1 });
return (
<div
ref={targetRef}
style={{
opacity: isInView ? 1 : 0,
transition: 'opacity 0.5s ease-out',
}}
>
I fade in when scrolled into view!
</div>
);
};
export default AnimatedComponent;
In this example, the AnimatedComponent starts with an opacity of 0, making it invisible. When at least 10% of the component scrolls into view (as set by the threshold option), the isInView state changes to true, and the component fades in with an opacity of 1.
In this article, we explore the Intersection Observer API and how to use it with React to track when elements are visible in the viewport. We cover the basics of the API, its advantages over older methods, and show a practical example by creating a custom React hook, useElementInView, to animate components when they come into view.
That's all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.