Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 952
poldark Avatar asked Sep 03 '25 16:09

poldark


2 Answers

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

like image 56
Shubham Khatri Avatar answered Sep 05 '25 05:09

Shubham Khatri


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

like image 30
Ali Taghipour Avatar answered Sep 05 '25 07:09

Ali Taghipour