Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use constructors in React components?

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?

like image 615
Cyval Avatar asked Aug 02 '16 05:08

Cyval


1 Answers

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 () {
  super()
  this.state = {
    // internal state
  }
}

Or if you have the class property syntax available (e.g. via Babel) you can forgo declaring a constructor if all you are using it for is to initialise the state:

class Example extends React.Component {
  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.

like image 130
sdgluck Avatar answered Oct 25 '22 11:10

sdgluck