0

I saw different examples where some people use state while others use this.state. I still don't understand when to use what. In examples using Mapbox or Meteor I only see this.state.

ex1:

export default class SomeComponent extends Component {
    state = { someState }
    render() {
        return (
          <Something-to-render-that-uses-state>
        );
    }
}

ex2:

export default class SomeComponent extends Component {
    constructor(props) {
        super(props);
        this.state = { someState }
    }
    render() {
        return (
          <Something-to-render-that-uses-state>
        );
    }
}
monchisan
  • 590
  • 8
  • 24

2 Answers2

0

when you define a variable in class as Object class property initialized, you don't need to make use of this keyword, simply writing state = { someState } is enough, However if you want to define a class variable in a function or a constructor, you need to make use of this keyword to specify what scope the variable belongs to

export default class SomeComponent extends Component {
    constructor(props) {
        super(props);
        this.state = { someState }
    }

    render() {
        return (
          <Something-to-render-that-uses-state>
        );
    }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

The state = {} declaration is a class property, which is currently not part of the JavaScript language. Certain utilities such as Babel will compile this into legal JavaScript code.

So it's exactly the same thing. Take a look at the JavaScript that babel transpiles the code into. There is no difference.

wobsoriano
  • 12,348
  • 24
  • 92
  • 162