Nyi Nyi Hmue Aung
Nyi Nyi Hmue Aung

Reputation: 736

How to get the updated state value in intersection observer React?

I have been struggling to find the solution to this problem for ages. If you have the answer, I would appreciate it. I have a component in which I want to use Intersection Observer. When a certain element is visible in the viewport, the function will be called to do something. But the problem is, when that function is called, you don't have the most updated state values in that function. Let me show it to you with a code example.

Intersection Observer

 const [someState,setSomeState] =useState(someVal)

 useEffect(() => {
    if (!isInfinite || !infiniteLoadingRef || !infiniteLoadingRef.current)
      return;
    const options = {
      root: null,
      rootMargin: "0px",
      threshold: 0,
    };
    const observer = new IntersectionObserver(handleObserver, options);
    observer.observe(infiniteLoadingRef.current);
  }, [infiniteLoadingRef]);

The function that gets called when a certain element is visible in the viewport

 const handleObserver = (entries: any, observer: any) => {
    if (entries[0].isIntersecting) {
      console.log(someState);
    }
  };


We have a state called someState and for some reason, that state gets updated and the entire component rerendered. Only after someState value changed, the handleObserver will be called. I am using someState inside that handleObserver and I don't get the most updated state's value. How do I get the most updated someState value in handleObserver? I tried putting someState as a dependency in my useEffect, but I got into an infinite loop. Please help me figure out this problem.

Upvotes: 2

Views: 2869

Answers (1)

Georgy
Georgy

Reputation: 1939

Try to use useCallback. It should keep the actual someState inside handleObserver:

const handleObserver = useCallback((entries: any, observer: any) => {
  if (entries[0].isIntersecting) {
    console.log(someState);
  }
}, [someState]);

Upvotes: 1

Related Questions