Skip to content

horchatajs/lazy-loading-react

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Aprende como implementar Lazy Loading a tus imagenes con Intersection Observer API y React JS

Hook useInfiniteScroll

import { useRef, useEffect } from "react";

export const useInfiniteScroll = ({ element, fetch }) => {
  const loader = useRef(fetch);

  const observer = useRef(
    new IntersectionObserver(
      (entries) => {
        const first = entries[0];
        if (first.isIntersecting) {
          loader.current();
        }
      },
      { threshold: 0.5 }
    )
  );

  useEffect(() => {
    loader.current = fetch;
  }, [fetch]);

  useEffect(() => {
    const currentElement = element;
    const currentObserver = observer.current;

    if (currentElement) {
      currentObserver.observe(currentElement);
    }
    return () => {
      if (currentElement) {
        currentObserver.unobserve(currentElement);
      }
    };
  }, [element]);
};

About

Ejemplo de lazy loading en imagenes con React JS

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published