2

Warning: 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 useEffect cleanup function.

useEffect(() => {
    const unsubscribe = streamCourses({
      next: (querySnapshot) => {
        const task = querySnapshot.docs.map((docSnapshot) => 
            mapDocTask(docSnapshot)
          );
        setCourseDetails(task);
      },
      error: (error) => console.log(error),
    });
    return unsubscribe;
  }, [setCourseDetails]);
P A T Himaranga
  • 111
  • 1
  • 2
  • 5

1 Answers1

5

I had a similar issue to this. What I had to do to solve it was two things:

(1) I created a State boolean isMounted which was set to true by default and was used to wrap the contents of my useEffects so that the contents of my useEffects would only run if the screen was mounted.

(2) I created a useEffect dedicated solely to cleanup. Meaning this useEffect had nothing besides a return statement in it which set the various State variables I had to their default values.

Example:

useEffect(() => {
    if (isMounted) {
        const unsubscribe = streamCourses({
          next: (querySnapshot) => {
            const task = querySnapshot.docs.map((docSnapshot) => 
                mapDocTask(docSnapshot)
              );
            setCourseDetails(task);
          },
          error: (error) => console.log(error),
        });
        return unsubscribe;
    }
  }, [setCourseDetails]);

useEffect(() => {
    return () => {
        setCourseDetails(null);
        setIsMounted(false);
    }
}, []);

man517
  • 419
  • 5
  • 9