0

useeffect is run on each rerender to prevent that i pass an empty array

React.useEffect(()=>{},[])

And to fire useeffect on state change of let's say count state variable

React.useEffect(()=>{},[count])

And if i have more of one state variable

React.useEffect(()=>{},[count, somethingelse])

My question is how to know which state variable caused the firing on useeffect hook

EDIT:

For people who are still checking this You can just do the following you can have multiple useEffect function

React.useEffect(()=>{},[count])

this will fire when count will change

React.useEffect(()=>{},[somethingelse])

this will fire when somethingelse will change

Abd
  • 497
  • 4
  • 14

1 Answers1

-2

So the useEffect is run when the state changes, you will definitely know what is the value of the state. For example:

useEffect(() => {
if(count){
  ...code
}
} , [count, somethingelse])

So basically you can add conditions to check if the value of the state is your desired value and run the desired code then.

Farrukh Rashid
  • 185
  • 1
  • 9
  • my question is which one caused the useffect function to fire – Abd Sep 05 '21 at 13:02
  • There is no inbuilt api provided by react itself to know that. Instead what we usually do is we just check the states in the useEffect if it is the desired value, only then the code for that state runs. Also, there are more elegant solutions provided here: https://stackoverflow.com/questions/55187563/determine-which-dependency-array-variable-caused-useeffect-hook-to-fire – Farrukh Rashid Sep 05 '21 at 13:44