79295272

Date: 2024-12-19 18:35:24
Score: 7 🚩
Natty: 4
Report link

Hey @j_quelly I use same solution what u, but it doesn't help. I've set the conditionall on entry.isIntersecting && and isIntersected (I need it to display animation once), but infinity loop still goes on. When i run useEffect with observerObject into component, everything is running like a charm, but for list elements it's a lot lines of code, that's why I want to encapsulated it to customHook.

Source Code

useIntersectionListObserver.ts

import { useEffect, useState, useCallback, useRef, MutableRefObject } from "react";

export const useIntersectionListObserver = (
  listRef: MutableRefObject<(HTMLDivElement | null)[]>,
  options?: IntersectionObserverInit
) => {
  const [visibleItems, setVisibleItems] = useState(new Set<number>());
  const [hasIntersected, setHasIntersected] = useState(false);
  const observerRef = useRef<IntersectionObserver | null>(null);

  const observerCallback = useCallback(
    (entries: IntersectionObserverEntry[]) => {
      entries.forEach((entry) => {
        const target = entry.target as HTMLDivElement;
        const index = Number(target.dataset.index);

        if (entry.isIntersecting && !hasIntersected) {
          setVisibleItems(
            (prevVisibleItems) => new Set(prevVisibleItems.add(index))
          );
          index === listRef.current.length - 1 && setHasIntersected(true);
        } else {
          setVisibleItems((prevVisibleItems) => {
            const newVisibleItems = new Set(prevVisibleItems);
            newVisibleItems.delete(index);
            return newVisibleItems;
          });
        }
      });
    },
    [hasIntersected, listRef]
  );

  useEffect(() => {
    if (observerRef.current) {
      observerRef.current.disconnect();
    }

    observerRef.current = new IntersectionObserver(observerCallback, options);

    const currentListRef = listRef.current;
    currentListRef.forEach((item) => {
      if (item) {
        observerRef.current.observe(item);
      }
    });

    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, [listRef, options, observerCallback]);

  return { visibleItems
 };
};

Any help in identifying the cause of the infinite loop and how to fix it would be greatly appreciated.

Reasons:
  • Blacklisted phrase (1): appreciated
  • Blacklisted phrase (0.5): I need
  • Blacklisted phrase (1): Any help
  • RegEx Blacklisted phrase (3): Any help in identifying the cause of the infinite loop and how to fix it would be greatly appreciated
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @j_quelly
  • Low reputation (1):
Posted by: Mark_stuck