React useIntersectionObserver Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to use the useIntersectionObserver hook in React to observe the visibility changes of a given element. This hook can be used to track when an element becomes visible on the screen and trigger certain actions accordingly. By the end of this lab, you will be able to implement this hook in your React projects to create more interactive and dynamic user interfaces.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react(("`React`")) -.-> react/StylingGroup(["`Styling`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") react/StylingGroup -.-> react/css_in_react("`CSS in React`") subgraph Lab Skills react/jsx -.-> lab-38389{{"`React useIntersectionObserver Hook`"}} react/event_handling -.-> lab-38389{{"`React useIntersectionObserver Hook`"}} react/conditional_render -.-> lab-38389{{"`React useIntersectionObserver Hook`"}} react/hooks -.-> lab-38389{{"`React useIntersectionObserver Hook`"}} react/use_state_reducer -.-> lab-38389{{"`React useIntersectionObserver Hook`"}} react/css_in_react -.-> lab-38389{{"`React useIntersectionObserver Hook`"}} end

React useIntersectionObserver Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To observe visibility changes for a given element, follow these steps:

  1. Use the useState() hook to store the intersection value of the given element.
  2. Create an IntersectionObserver with the given options and an appropriate callback to update the isIntersecting state variable.
  3. Use the useEffect() hook to call IntersectionObserver.observe() when mounting the component and clean up using IntersectionObserver.unobserve() when unmounting.

Here's an example implementation:

const useIntersectionObserver = (ref, options) => {
  const [isIntersecting, setIsIntersecting] = React.useState(false);

  React.useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      setIsIntersecting(entry.isIntersecting);
    }, options);

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      observer.unobserve(ref.current);
    };
  }, [ref, options]);

  return isIntersecting;
};

You can use the useIntersectionObserver hook like this:

const MyApp = () => {
  const ref = React.useRef();
  const onScreen = useIntersectionObserver(ref, { threshold: 0.5 });

  return (
    <div>
      <div style={{ height: "100vh" }}>Scroll down</div>
      <div style={{ height: "100vh" }} ref={ref}>
        <p>{onScreen ? "Element is on screen." : "Scroll more!"}</p>
      </div>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useIntersectionObserver Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like