Search code examples
reactjsreact-nativereact-hooksuse-effect

How to return a useEffect with only if statements in React Native


I'm using a useEffect to define a variable value when I enter in the page, but sometimes I get the following warning:

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.

Here is my code of the useEffect function:

useEffect(() => {
        if(hierarchy == '1'){
            setJob('Investigador')
        }
        if(hierarchy == '2'){
            setJob('Administrador')
        }
        if(hierarchy == '0'){
            setJob('Novo Utilizador')
        }
}, [])

I know that i should return something in the function to clean it up, but since i'm using only if's and not a const, how can I return in order not have this error?


Solution

  • You should use a cleanup function when you set states in your app. Consider using 'mounted' variable, to tell whether it should skip the call to setState or not.

        import React, { useEffect, useState, useRef } from "react";
        
        //inside component:
        const mounted = useRef(true);
        useEffect(() => {
        mounted.current = true;
         if (mounted.current) {
                if(hierarchy == '1'){
                    setJob('Investigador')
                }
                if(hierarchy == '2'){
                    setJob('Administrador')
                }
                if(hierarchy == '0'){
                    setJob('Novo Utilizador')
                }
        }
         return () => (mounted.current = false);
        }, [])