1

In a react class component, I have a new function to add to a lifecycle method. I am trying to figure out if it is better to have:

componentDidUpdate() {
     const myFunc = () => {
          // Do something
     }
     myFunc();
}

Or:

const myFunc = () => {
     // Do something
}
componentDidUpdate() {
     this.myFunc();
}

My concern with having myFunc() function created inside of componentDidUpdate, is that the function will get created every time the component re-renders, as opposed to only getting created once. Am I correct in this assumption?

Ryan Williams
  • 119
  • 2
  • 8
  • Does this answer your question? [When to use 'componentDidUpdate' method?](https://stackoverflow.com/questions/38759703/when-to-use-componentdidupdate-method) – André Mar 10 '23 at 10:42
  • Yes. And even better, do not use an arrow function with class field syntax, so that the function does not get created for every instance of the component but really only once. – Bergi Mar 10 '23 at 10:42

1 Answers1

0

Correct. If you define myFunc function inside componentDidUpdate method, it will be created every time the component updates. If you define myFunc function outside of the componentDidUpdate method, it will only be created once when the component mounts.

Invulner
  • 842
  • 2
  • 11