Cyval Cyval - 4 months ago 21
React JSX Question

React + Javascript ES6 Classes - When to use Constructors

I always write React code, particularly in ES6 Classes. But my question is, when do we use

constructor(props)
in React Components? Does the
constructor(props)
line has something to do with the rendering of the component together with its props?

Answer

The accepted answer is incorrect (perhaps just a misuse of the word "render").

As I explain in my comment on it the constructor of a React component is executed once the first time the component is mounted, or instantiated. It is never called again in subsequent renders.

Typically the constructor is used to set-up a component's internal state, for example:

constructor () {
  this.state = {
    // internal state
  }
}

Does the constructor(props) line has something to do with the rendering of the component together with its props?

The constructor does not directly dictate what is rendered by a component.

What is rendered by a component is defined by the return value of its render method.