0

So far I understand there are two ways to define state in react class.

The first as many people use them, is as follows:

import React, { Component } from "react";
import { View, Text } from "react-native";

export default class Test extends Component {

  constructor (props) {
     super(props)
     this.state = {
       text: 'hello'
     }
  }

  render() {
    return (
      <View>
        <Text>{this.state.text}</Text>
      </View>
    );
  }
}

The second one is as follows:

import React, { Component } from "react";
import { View, Text } from "react-native";

export default class Test extends Component {

  state = {
     text: "hello"
  }

  render() {
    return (
      <View>
        <Text>{this.state.text}</Text>
      </View>
    );
  }
}

The difference is at using constructor or not. What is the effect and is there any difference at all between the two? If there is, which one should I use?

Thank you!

Eric Ahn
  • 391
  • 2
  • 7
  • 18
  • Possible duplicate of [init state without constructor in react](https://stackoverflow.com/questions/42993989/init-state-without-constructor-in-react) – imjared Jan 22 '19 at 05:17
  • Possible duplicate of [Is it better to define state in constructor or using property initializers?](https://stackoverflow.com/questions/37788342/is-it-better-to-define-state-in-constructor-or-using-property-initializers) – Just code Jan 22 '19 at 05:23
  • Thanks to both of you for the reference!! :) – Eric Ahn Jan 22 '19 at 05:30

2 Answers2

1

Both methods are correct. Make sure you have support for class properties enabled in the babelrc. If you are using CRA both will work. Constructor one is better on the eyes if you want to seed the initial state from props.

Perpetualcoder
  • 13,501
  • 9
  • 64
  • 99
0

Both methods are fine. Second one is the short-hand method

Umair Farooq
  • 1,763
  • 13
  • 16