Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React defining state without a constructor [duplicate]

I've seen some react developers define state without a constructor. I like the fact that is simplifies the code, but is it safe to do so?

class Dog extends React.Component {
   state = { sound: 'Woof' }
   return (
      <p>Dog says { this.state.sound }</p>
   )
}

I apologize in advance for the over simplified example.

like image 475
camloken Avatar asked Apr 21 '17 15:04

camloken


People also ask

How do I set state in react without constructor?

React State without a Constructor In React, state is used in a React class component. There you can set initial state in the constructor of the class, but also access and update it with this.state and this.setState, because you have access to the class instance by using the this object. import React, { Component } from 'react';

Is there a constructor in React components?

You have learned, that there is no constructor needed to set the initial state of a React component by using class field declarations in enviroments where these are supported. Moreover, you have experienced how higher-order components or render prop components can be used to make a functional component stateful.

How to access and set state in react class?

In React, state is used in a React class component. There you can set initial state in the constructor of the class, but also access and update it with this.state and this.setState, because you have access to the class instance by using the this object. import React, { Component } from 'react'; const list = ['a', 'b', 'c'];

What is a state object in react?

The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.


1 Answers

Its exactly the same thing. Take a look at the javascript that babel transpiles the code into. There is no difference.

like image 114
Shaun Sweet Avatar answered Oct 19 '22 20:10

Shaun Sweet