search
HomeWeb Front-endJS TutorialHow to use the Intersection Observer in React

Today we will explore how to use the intersection observer API in React with some examples.

Mozilla web documentation describes the intersection observer API as:

allows code to register a callback function that runs whenever an element they want to monitor enters or leaves another element (or the viewport), or when the value by which the two intersect changes of a requested amount. This way, sites no longer need to do anything on the main thread to observe this type of intersection of elements, and the browser is free to optimize intersection management as it sees fit.

In short, it allows us to detect when a certain element is visible in the viewport, this only happens when the element meets the desired intersection ratio.

Como utilizar o Intersection Observer no React

As you can see, if you scroll down the page the intersection ratio will increase until it reaches the projected limit and at that moment the function that executes a callback is triggered.


First step

const observer = new IntersectionObserver(callbackFunction, options)
observer.observer(elementToObserver)

The intersection observer constructor object needs two arguments:

  1. A callback function
  2. Options

That's all, we're 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:

const options = {
  root: null,
  rootMargin: "0px",
  threshold: 1
}
  • root: The element that is used as a viewport to check the visibility of the target. Must be the target's ancestor. Defaults to browser viewport if not specified or null.
  • rootMargin: This set of values ​​is used to increase or decrease each side of the root element's bounding box before calculating the intersections, the options are similar to those for margin in CSS.
  • threshold: A single number or an array of numbers that indicates at what percentage of the target's visibility the observer callback should run, ranges from 0 to 1.0, where 1.0 means each pixel is visible in the viewport.

Using in React

Como utilizar o Intersection Observer no React

Now we will see an implementation of the intersection observer API in React.

const observer = new IntersectionObserver(callbackFunction, options)
observer.observer(elementToObserver)
  1. Start with a reference to the element we want to observe, use the react hook useRef.
  2. Create a state variable isVisible, we will use it to display a message whenever our box is in the viewport.
  3. Declare the callback function that will receive an array of IntersectionObserverEntries as a parameter, within this function we take the first and only entry and check if it is intersecting with the viewport and if it is then we call setIsVisible with the value of entry.isIntersecting (true / FALSE).
  4. Create the options object with the same values ​​as the image.
  5. Add the useEffect react hook and create an observer constructor using the callback function and options we just created before. It's optional in our case, but it can return a cleanup function to unwatch our target when the component is unmounted.
  6. Set the useRef variable on the element we want to observe.
const options = {
  root: null,
  rootMargin: "0px",
  threshold: 1
}
  1. Let's add some style to this html.

Como utilizar o Intersection Observer no React

  1. That's all we need, simple and easy!

Remember, this is just a basic implementation and there are several ways to do this.

Como utilizar o Intersection Observer no React


Now we will implement the same code we did previously, but separating all the logic in a nu hook called useElementOnScreen.

const containerRef = useRef(null)
const [isVisible, setIsVisible] = useState(false)

const callbackFunction = (entries) => {
  const [entry] = entries
  setIsVisible(entry.isIntersecting)
}

const options = {
  root: null,
  rootMargin: "0px",
  threshold: 1.0
}

useEffect(() => {
  const observer = new IntersectionObserver(callbackFunction, options)
  if (containerRef.current) observer.observe(containerRef.current)

  return () => {
    if (containerRef.current) observer.unobserve(containerRef.current)
  }

}, [containerRef, options])

return (
  <div classname="app">
    <div classname="isVisible">{isVisible ? "IN VIEWPORT" : "NOT IN VIEWPORT"}</div>
    <div classname="section"></div>
    <div classname="box" ref="{containerRef}">Observe me</div>
  </div>
)

  1. Create a new function called useElementOnScreen with parameter options
  2. Move the entire useRef, useState and useEffect inside our new hook.
  3. Now the only thing missing from our hook is the return statement, we pass isVisible and containerRef as an array.
  4. ok, we're almost there, we just need to call it in our component and see if it works!
<div classname="box" ref="{containerRef}">Observe me</div>

1- Import the newly created hook into our component.
2 - Initialize it with the options object.
3 - This is how we finish.

Congratulations, we have successfully used the intersection observer API and even created a hook for it!


Credits

Intersection Observer using React, originally written by producthackers

Thank you for reading this article. I hope I can provide you with some useful information. If so, I would be very happy if you would recommend this post and click the ♥ button so more people can see this.

The above is the detailed content of How to use the Intersection Observer in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool