Search code examples
javascriptreactjsuse-effectmern

Why does useEffect fires on page reload even when the dependency is not changing?


I have this useEffect in one of my react components.

const [photo,setPhoto]=useState();

useEffect(()=>{
    console.log("inside photo useEffect")
    setIsLoading(true);

    fetch("/uploadPhoto",{
        method:"post",
        body:photo
    })
    .then(res=>res.json())
    .then(data=>{
        setPhotoURL(data.secure_url);
        setIsLoading(false)
    })
    .catch(err=>{
        console.log(err);
    })
},[photo])

I want to fire this useEffect only when the value of "photo" changes. But it gets fired whenever the page is reloaded.

How to achieve this?


Solution

  • I found a way to do this. It seems that useEffect by default executed on every render irrespective of the dependencies. We use dependencies as second parameter to define when the useEffect should be executed again.

    I changed my code like this and it worked.

    useEffect(()=>{
        if(photo){ 
            console.log("inside photo useeffect")
            setIsLoading(true);
            
    
            fetch("/uploadPhoto",{
                method:"post",
                body:photo
            })
            .then(res=>res.json())
            .then(data=>{
                setPhotoURL(data.secure_url);
                setIsLoading(false)
            })
            .catch(err=>{
                console.log(err);
            })
        }
    },[photo])
    

    It gets executed only if "photo" has a value.