Home > database >  How to manage dependency arrays with useEffect
How to manage dependency arrays with useEffect

Time:10-02

Suppose I've got two variables varA and varB. I only want to do something to varA in the event the varB changes. I could write something to the effect of...

useEffect(()=> {
  DO SOMETHING TO varA;
}, [varB])

If I do this REACT will throw a warning in the console about a missing dependenecy, varA and ask that it be added to the array. But doing so will create behavior I do not want. How can I handle the warning in this situation?

CodePudding user response:

One of the rules of React hooks is that useEffect must include all variables that it references in its dependency array. That's why you're getting the error. You can have additional variables, like varB, but you cannot exclude one, otherwise you could run into some wonky behavior.

A way around it is to use a ref, which allows you to store the value in a way that never triggers a render. The ref will need to be included in the dependency array, but since it never changes it won't trigger the useEffect again.

const varARef = useRef(varA)

useEffect(()=> {
  DO SOMETHING TO varARef.current;
}, [varARef, varB])

Note that if you do want varARef.current to stay in sync with varA, you'll want to add a line for that:

const varARef = useRef(varA)
varARef.current = varA

useEffect(()=> {
  DO SOMETHING TO varARef.current;
}, [varARef, varB])

CodePudding user response:

If you have to update the state of a variable using its current state the best way to do it is using a callback inside setState.

If you change your code like this no issue will be triggered.

[varB, setVarB] = useState("");
[counter, setCounter] = useState(0);

useEffect(()=>{
 setCounter(currentCounter => currentCounter 1);
},[varB]) // No warning here

Full answer: useEffect has a missing dependency when updating state based on current value

  • Related