3

I want to write the equivalent of componentDidMount so the docs tell me to use an emptyArray

useEffect(() => {
    console.log(props.myProp1)
    console.log(props.myProp2)

    console.log('DIDMOUNT.');
}, [])

But everytime I try to access a variable that is not part of the dependency array inside the useEffect callback, the warning is:

React Hook useEffect has missing dependencies: 'props.myProp1' and 'props.myProp2'. Either include them or remove the dependency array react-hooks/exhaustive-deps

Which defeats the purpose of having an empty-array (to simulate componentDidMount) ?

With Classes I simply write

componentDidMount() {
    console.log(props.myProp1)
    console.log(props.myProp2)
}

, and can access any variable that the Class is aware of;

UPDATED: I voted to close the question, as a comment below pointed to a duplicate.

joedotnot
  • 4,810
  • 8
  • 59
  • 91
  • The argument is that if you want to do something with `myProp1`, if that changes, you should want to do something different with it when it changes. Whether the rule *should* be ignored or not depends on what you're actually trying to do with those props. – CertainPerformance Nov 20 '21 at 16:49
  • answered here https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook – Andrej Kirejeŭ Nov 20 '21 at 16:55
  • @Andrej, wow the way I read the answer is that I have to actually disable the ruling, Seriously, I didn't have to disable any rules with Class components just to log a variable – joedotnot Nov 20 '21 at 17:02
  • Then you need to fill in an issue with react developers. It is a known behavior of useEffect. – Andrej Kirejeŭ Nov 20 '21 at 17:05
  • Ok Thank you Andrej for pointing to the existing answer. – joedotnot Nov 20 '21 at 17:21

0 Answers0