3

Using Constructor:

import { Text } from 'react-native';
import Component from 'react';

class Blink extends Component {
    constructor(props) {
      super(props);
      this.state = {test: "Hello"};
}

Without constructor:

import { Text } from 'react-native';
import Component from 'react';

class Blink extends Component {
    state = { test:"Hello" }
}

The code works in the same way. But what's the difference? Which one is better?

Wen Seng Tee
  • 95
  • 1
  • 7
  • 3
    https://stackoverflow.com/questions/30668326/what-is-the-difference-between-using-constructor-vs-getinitialstate-in-react-r – Hoàng Vũ Anh Jul 25 '18 at 04:51

1 Answers1

5

It's just a matter of preference! Here's an article I found about the different ways to initialize a component: https://daveceddia.com/where-initialize-state-react/

sshaul
  • 99
  • 2
  • It's also worth noting that with componentDidMount() being deprecated now, the constructor is a great place to run some pre-render code on the first mount. – trevdev Jul 25 '18 at 15:30