Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useOnScreen causing issue while unmounting #19

Open
irf4nmohd opened this issue Oct 14, 2021 · 3 comments
Open

useOnScreen causing issue while unmounting #19

irf4nmohd opened this issue Oct 14, 2021 · 3 comments

Comments

@irf4nmohd
Copy link

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
Copy link

Async10 commented Oct 31, 2021

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
Copy link
Author

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
Copy link

Async10 commented Nov 1, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants