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?

1

1 Answer 1

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/

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

1 Comment

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.

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.