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!

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.