Search code examples
javascriptreactjsreact-hooksreact-reduxlazy-loading

how to stop fetching again image if already fetch?


how to stop fetching again image if already fetch ? I am using below plugin to check whether element come in view port or not. but issue is when I scroll down it fetch image which is correct behaviour but when I move up it hide the image again . If I move down again it again fetch the image ?

how to prevent fetching again and again image . If already come in DOM don't remove .

https://www.npmjs.com/package/react-intersection-observer

import * as React from "react";
// @ts-ignore Wrong type
import { createRoot } from "react-dom/client";
import { useInView } from "react-intersection-observer";
import ScrollWrapper from "./elements/ScrollWrapper";
import "./styles.css";

function App() {
  const { ref, inView } = useInView({
    threshold: 0
  });

  return (
    <>
      <div style={{ height: "200vh" }}>eeeeee</div>
      <div ref={ref} className="inview-block">
        <h2>
          <img
            src={
              inView
                ? "https://inviewimaging.com/wp-content/uploads/2015/04/Inview-Graphic.png"
                : null
            }
            alt=""
          />
        </h2>
      </div>
    </>
  );
}

const root = createRoot(document.getElementById("root"));
root.render(<App />);

here is my code ... any suggestion ?

https://codesandbox.io/s/useinview-forked-74y015?file=/src/index.tsx:0-786


Solution

  • You can set triggerOnce:true in useInView like this :

      const { ref, inView } = useInView({
        threshold: 0,
        triggerOnce:true,
      });