Home > Software design >  Only one ComponentDidMount per class component?
Only one ComponentDidMount per class component?

Time:10-14

This is an easy question I know but I can't find the answer to this for the life of me.

Can you only have on ComponentDidMount method per class component in React? Is it bad to have multiple? Will it work?

CodePudding user response:

Yes you can only have one componentDidMouny per class. But you could use an useEffect without adding dependencies. This behaves the same as a componentDidMount.

CodePudding user response:

If you have multiple componentDidMount it will only run the last one (the others get overridden by the last declaration). See also: https://codesandbox.io/s/relaxed-feather-gc6nr?file=/src/App.js.

  • Related