React.js state without ‘Constructor’

Michael S
2 min readDec 27, 2018

--

state without constructor

I have been using with ‘constructor’ and ‘super’, However, I happened to see following way below to declare local state of a component for the first time when I had a outsourcing project.

class FeedCommentList extends Component<Props, State> {  state: State = {    isLoading: true,    number: 6  };...}

After the project, I figured out how these are different from each other briefly(There are more to dig out though…). Simple way to compare both is using babel ‘Try out’ feature.

I put both cases into Babel ‘Try out’ feature.

INPUT

1.Input on ‘Try out’ feature with ‘constructor’

class App extends React.Component {
constructor(props) {
super(props);
this.state = { lat: null, errorMessage: '' };
}
}

2.Input on ‘Try out’ feature

class App extends React.Component {
state = { lat: null, errorMessage: '' };
}

OUTPUT

1.Output from ‘Try out’ feature with ‘constructor’

class App extends React.Component {
constructor(props) {
super(props);
this.state = { lat: null, errorMessage: '' };
}
}

2.Output from ‘Try out’ feature

class App extends React.Component {
constructor(...args) {
var _temp;
return _temp = super(...args),
this.state = { lat: null, errorMessage: '' },
_temp;
}
}

Reference :

  1. https://reactjs.org/docs/react-component.html
  2. https://reactjs.org/docs/state-and-lifecycle.html
  3. https://itnext.io/how-to-properly-define-state-in-react-components-47544eb4c15d
  4. https://www.robinwieruch.de/react-state-without-constructor/
  5. Modern React with Redux by Stephen Grider

I am blogging what I’ve learned to find later here for myself. If you happened to read this shit and there is wrong information, it would be appreciated to add a comment below.

--

--

Michael S
Michael S

Written by Michael S

#Sales#Coding#Food#FoodTech#Writing#

No responses yet