Search code examples
javascriptreactjstypescriptreact-hooksuse-effect

use effect run only when a state becomes false


i use react and i have a state with name isModalOpen.

const [isModalOpen, setIsModalOpen] = useState<boolean>(false);

i have a useEffect function

useEffect(() => {},[]);

i want my use effect run every time that my isModalOpen become to false(only false)

i wrote

useEffect(()=>{},[!isModalOpen])

but this method run everytime that isModalOpen changed(true to false or false to true)


Solution

  • The dependency array to useEffect is meant to inform useEffect to run when there is a change in value. So whether you pass isModalOpen or !isModalOpen, its one and the same thing as it just checks whether the value changed i.e false to true or true to false.

    The way to conditionally execute something is to aadd a condition in the callback function

    useEffect(()=>{
        if(!isModalOpen) {
            // write your code here
        }
    
    },[isModalOpen]);
    

    However, if at some point you want to access the old and new value both in useEffect, you can implement a usePrevious hook as mentioned in the React Hook FAQs