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.

5
  • 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. Commented Nov 20, 2021 at 16:49
  • answered here stackoverflow.com/questions/55840294/… Commented Nov 20, 2021 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 Commented Nov 20, 2021 at 17:02
  • Then you need to fill in an issue with react developers. It is a known behavior of useEffect. Commented Nov 20, 2021 at 17:05
  • Ok Thank you Andrej for pointing to the existing answer. Commented Nov 20, 2021 at 17:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.