Eric Ahn
Eric Ahn

Reputation: 401

Proper way of defining/initializing state in reactjs or react-native

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!

Upvotes: 0

Views: 434

Answers (2)

Perpetualcoder
Perpetualcoder

Reputation: 13571

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.

Upvotes: 1

Umair Farooq
Umair Farooq

Reputation: 1823

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

Upvotes: 0

Related Questions