1

I am having an issue with the useEffect hook where I would only like a conditional statement inside the callback to execute if, and only if, a specific dependency was changed. For example:

const [index, setIndex] = React.useState(3);
const [dep, setDep] = React.useState(1);
React.useEffect(() => {
  if (index === 0) {
    if (dep triggered the callback and not index) {
       setIndex(dep);
    }
  }
}, [index, dep]);

setIndex(0); // I do not want `setIndex(dep)` to execute yet
setDep(5);   // Now, I want `setIndex(dep)` to execute

How would I achieve this logic in React? Do I need to use a different hook?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
rolling_codes
  • 15,174
  • 22
  • 76
  • 112

1 Answers1

0

Try this :

const [index, setIndex] = React.useState(3);
const [dep, setDep] = React.useState(1);
const [flag,setFlag] = useState(false);

React.useEffect(() => {
  setIndex(0);
  setFlag(true)
}, [dep]);

React.useEffect(() => {
  if (index === 0 && flag == true) {
    if (dep triggered the callback and not index) {
        setIndex(dep);
    }
  }
  setFlag(false)
}, [flag]);

setIndex(0); // I do not want `setIndex(dep)` to execute yet
setDep(5);
rolling_codes
  • 15,174
  • 22
  • 76
  • 112
yanir midler
  • 2,153
  • 1
  • 4
  • 16
  • That won't work because your second `useEffect` hook references `dep` and must be required in the dependency array – rolling_codes Jun 07 '22 at 13:49
  • what about the if statement that is not valid typescript? that should be removed, right? – rolling_codes Jun 07 '22 at 13:53
  • The if will work only when the first useEffect will run. So the dep will triget the if like the text you wrote inside the if. – yanir midler Jun 07 '22 at 13:55
  • also, i would still need to include `index` and `dep` as dependencies in your second `useEffect` hook because they are referenced in the callback – rolling_codes Jun 07 '22 at 13:55
  • no,because you want to triget the sec useEffect only when dep updated. so the flag state will be true only when this first useEffect will run . index === 0 && flag == true -> only if flag equle true, than the if statmante will run. – yanir midler Jun 07 '22 at 13:57