Reputation: 2235
I need to update the current value of a React state based on its current value. However, using the current state will trigger the warning: React Hook useEffect has a missing dependency
. How can I update the state?
For simplicity suppose that I have to count the times another state is updated:
[myState, setMyState] = useState("");
[counter, setCounter] = useState(0);
useEffect(()=>{
setCounter(counter+1);
},[myState]) // React Hook useEffect has a missing dependency: 'counter'
However, I can't add counter
among the dependencies since the useEffect will enter in an infinite loop (since hook will be triggered again because of counter
change).
Upvotes: 0
Views: 367
Reputation: 2235
The best way to implement this type of change is using a callback inside the setState
method. By using a callback we can access the current value of our state, without the need to reference the object containing the state directly. In this way, no warning is issued and the counter can be implemented directly.
[myState, setMyState] = useState("");
[counter, setCounter] = useState(0);
useEffect(()=>{
setCounter(currentCounter => currentCounter+1);
},[myState]) // No warning here
Or if you need more complex actions:
useEffect(()=>{
setCounter(currentCounter => {
//do stuff
return currentCounter+1
});
},[myState]) // No warning here
Full documentation: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Upvotes: 2