WebDevSimplified / useful-custom-react-hooks

1.95k stars 687 forks source link

useOnScreen causing issue while unmounting #19

Open irf4nmohd opened 3 years ago

irf4nmohd commented 3 years ago

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a use effect cleanup function.

Async10 commented 3 years ago

This problem is caused by the callback passed to the IntersectionObserver. The callback calls setIsVisible which can, due to the asynchronous nature of the InserctionObserver, be called, when the component using useOnScreen is no longer mounted. To prevent this error setIsVisible should only be called when the component is mounted. A potential fix could like this.

useEffect(() => {
    let isActive = true;
    if (!ref.current) return
    const observer = new IntersectionObserver(
      ([entry]) => isActive && setIsVisible(entry.isIntersecting),
      { rootMargin }
    )
    observer.observe(ref.current)
    return () => {
      isActive = false;
      ref.current && observer.unobserve(ref.current)
    }
  }, [ref.current, rootMargin])
irf4nmohd commented 3 years ago

This problem is caused by the callback passed to the IntersectionObserver. The callback calls setIsVisible which can, due to the asynchronous nature of the InserctionObserver, be called, when the component using useOnScreen is no longer mounted. To prevent this error setIsVisible should only be called when the component is mounted. A potential fix could like this.

useEffect(() => {
    let isActive = true;
    if (!ref.current) return
    const observer = new IntersectionObserver(
      ([entry]) => isActive && setIsVisible(entry.isIntersecting),
      { rootMargin }
    )
    observer.observe(ref.current)
    return () => {
      isActive = false;
      ref.current && observer.unobserve(ref.current)
    }
  }, [ref.current, rootMargin])

if found the fix use=>useLayoutEffect instead of useEffect this will fix the problem

Async10 commented 3 years ago

This works too because useLayoutEffect fires synchronously. However according to the react docs using useEffect is preferred over using useLayoutEffect to avoid blocking visual updates.