5

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.

Ajith kumar
  • 123
  • 1
  • 12
  • what do you want to achieve? anyway `useEffect` is running _after_ render finished. Also there is no way _to stop render_. So better describe what do you believe that should help you with – skyboyer Nov 24 '19 at 14:38
  • you cannot `stop` a render, what do you want to achieve through this? – Agney Nov 24 '19 at 15:00
  • can I use the condition in the second parameter to control the re-run. – Ajith kumar Nov 24 '19 at 15:26

2 Answers2

5

No. You can't. useEffect will be runned every time provided variable changed.

You have two options:

  1. Stop function execution inside useeffect
    useEffect(() => {
       if (variableName!=5) return // do nothing if condition is not met
       // do something
    },[variableName]);
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
1

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

Ali
  • 468
  • 1
  • 8
  • 19