'how to control the re-running with useEffect
I have a little bit of doubt in the useEffect function. I am trying to stop the unnecessary condition with useEffect. the question is can I control the useEffect with condition and is it possible?. the example code,
it is normal code,
useEffect(() => {
// do something
},[variableName]);
my expectation code and question is,
useEffect(() => {
// do something
},[variableName == 5]); // if it's true, Does the useEffect control the re-run?
it's like an if condition and is it possible to stop the re-run. I know it's weird but just for my clear understanding.
Thank you.
Solution 1:[1]
No. You can't. useEffect will be runned every time provided variable changed.
You have two options:
- Stop function execution inside useeffect
useEffect(() => {
if (variableName!=5) return // do nothing if condition is not met
// do something
},[variableName]);
Solution 2:[2]
you can set a boolian state in your functional component and set it to true if a certain condition is met and use that state variable as your second parameter for useEffect hook
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ali |
