'React.useEffect dependency has a missing dependency
I want to use the checked value in useEffect but don't want to add it in dependency array as I don't want useEffect to be called on checked updation.
But I am getting the warning "React Hook useEffect has missing dependency :"checked".Either include it or remove the dependency array".
const[checked , setChecked] = React.useState(false);
useEffect(() = >{
if(data.length && !checked){
setChecked(true)
}
else{
//something
}
},[data]);
Solution 1:[1]
One way you can do this is with a usePrevious hook to track the last value of checked. If prevChecked and checked are not equal, then you would cancel early.
const[checked , setChecked] = React.useState(false);
const prevChecked = usePrevious(checked)
useEffect(() = >{
if (prevChecked !== checked) return
if(data.length && !checked){
setChecked(true)
}
else{
//something
}
},[data, prevChecked, checked]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stafford Rose |
