How to avoid memory leak in react native?

Viewed 110

I am trying to handle memory leak in the react native. I already follow many tutorials but no avail.

here is my original code

useEffect(() => {
        const unsubscribe = navigation.addListener('focus', () => {
            setLoading(true);
            async function fetchData() {
                try {
                    await dispatch(fetchProductComment(itemNum, ''));
                    await dispatch(fetchMultiBuy(itemNum, 'SIZES'));
                    ...
                } catch (err) {
                    console.log(err);
                } finally {
                    setLoading(false);
                }
            }

            fetchData();
        });
        return unsubscribe;
    }, [navigation]);

after looking around the tutorials I tried Boolean Flag method and Abort Controller Method to avoid memory leak . But these do not work.

***ABORT CONTROLLER METHOD***

useEffect(() => {
        let abortController = new AbortController();
        const unsubscribe = navigation.addListener('focus', () => {
            setLoading(true);
            async function fetchData() {
                ...
            }
            fetchData();
        });

        return () => {
            abortController.abort;
            unsubscribe;
        };
    }, [navigation]);



***BOOLEAN METHOD***

 useEffect(() => {
        let componentMounted = true;
        const unsubscribe = navigation.addListener('focus', () => {
            setLoading(true);
            async function fetchData() {
                ...
            }
            fetchData();
        });
    
        return () => {
            componentMounted = false;
            unsubscribe;
        };
    }, [navigation]);

These do not works. Any Ideas?

1 Answers

I too have the same issue..Could you please try this and comment if its still showing memory leak.

Im following up with the question.

 useEffect(() => {
          const controller = new AbortController();
          const  signal  = controller.signal;      
          (async () => {
            const response = await fetch(API_KEY, {signal});
              const news = await response.json();
                setNews(news.articles); // fetched JSON
            }
          )();
          
          return () => controller.abort();
        },[API_KEY])
Related