poldark
poldark

Reputation: 43

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)

Upvotes: 3

Views: 11618

Answers (3)

Hafiz Muhammad Bilal
Hafiz Muhammad Bilal

Reputation: 315

Dependency array in useEffect contains those values which cause re-rendering of the component upon change in those values. So have a condition to restrict your login as:

useEffect(()=>{
if(!isModalOpen){
//your logic
}
}, [isModalOpen])

Upvotes: 1

Ali Taghipour
Ali Taghipour

Reputation: 114

you should write like this not your sample because every time you write a state in dependencies

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

array useEffect triggers when it changes

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281656

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

Upvotes: 13

Related Questions