Reputation: 773
I'm using useEffect with several dependencies included in the dependency array, which are at the same time props. I want to ignore some dependencies (i.e. props.b) which are causing my page to render when these dependencies change; however, I have to include a dependency array because I want my useEffect to listen to other dependencies (i.e. props.a). This is my code very, very simplified:
const MyFunction(props){
const [c,setC] = useState([])
useEffect(()=>{
if (props.a){
let c0;
props.b.forEach((item)=>{
c0 = [...,c0.x]
})
setC(c0)
}
,[props.a])
return (
<div>
<OtherComponent
c={c}
/>
</div>
)
}
I don't know how to procede without getting a warning, as I really need to ignore props.b but not props.a
Upvotes: 3
Views: 3343
Reputation: 7717
useEffect takes a function and an array of dependencies. The function creates a closure (traps the variables within it at their current values), so you DO want any variable used to be in the dependency list because if it changes, you need that entire function to be recreated. Otherwise you get hard to find bugs.
Pass in all the props, it's OK. Since "c" is an array, pass in 'c' as well, and instead of "setC(...)" you can just c.push(...) to add to that array.
Finally, if you have your app wrapped in strict mode, then your component renders twice in a row. This is to prevent you from having side-effects. If you remove (temporarily) strict mode and look at your console logs, things may be as you expect.
Upvotes: 2
Reputation: 2737
It's not an error to have such a warning. It happens because you're using props.b
inside the useEffect
. Avoid the warning and go with your code. It won't be an issue.
Upvotes: 0
Reputation: 15520
If you use eslint, I'd suggest you to add these comments to ignore dependency
useEffect(()=>{
if (props.a){
let c0;
props.b.forEach((item)=>{
c0 = [...,c0.x]
})
setC(c0)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
,[props.a])
If you want to disable that behavior permanently, you can modify your .eslintrc
// Your ESLint configuration
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "off" //Set it `off`
}
}
BUT you need to keep in mind that react-hooks/exhaustive-deps
is like a safe-guard for your hooks. If you disable it permanently, that may cause some unexpected bugs. I'd suggest you use the first way which is only to disable dependency check on the line you want.
Upvotes: 1